两个栈实现队列
来源:互联网 发布:环境科学与工程知乎 编辑:程序博客网 时间:2024/05/17 02:15
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
初始思路:
1,2都空:压:1;出:错
1有2空:压:1–>2,压1 出:1–>2,出2
1空2有:压1,出:2
1,2都有: 压1,出2
class Solution{public: void push(int node) { if(stack2.size()==0){ while(stack1.size()!=0){ int tmp=stack1.top(); stack1.pop(); stack2.push(tmp); } } stack1.push(node); } int pop() { if(stack1.size()==0&&stack2.size()==0) return 0; if(stack2.size()==0){ while(stack1.size()!=0){ int tmp=stack1.top(); stack1.pop(); stack2.push(tmp); } } int result=stack2.top(); stack2.pop(); return result; }private: stack<int> stack1; stack<int> stack2;};
其实,压入的时候1有2空的时候不需要把1–>2,可以直接压1,因为出的时候1–>2,新压的会在2的底部。
class Solution{private: stack<int> stack1; stack<int> stack2;public: void push(int node) { stack1.push(node); } int pop() { if(stack2.size()<=0){ while(stack1.size()>0){ int i=stack1.top(); stack1.pop(); stack2.push(i); } } int j=stack2.top(); stack2.pop(); return j; }};
0 0
- 两个栈实现队列
- 两个队列实现栈
- 两个栈实现队列
- 两个栈实现队列
- 两个栈实现队列
- 两个队列实现栈
- 两个栈实现队列
- 两个 栈 实现队列
- 两个栈实现队列
- 两个队列实现栈
- 两个栈实现队列
- 两个栈实现队列
- 两个队列实现栈
- 两个栈实现队列
- 两个栈实现队列
- 两个栈实现队列
- 队列--两个栈实现
- 两个队列实现栈
- DHCP以太报文全码分析--(含完整数据包内容)
- Monte Carlo Sampling Methods-- 蒙特卡洛采样方法
- 学习Android中服务总结
- 汉诺塔的实现
- 数据库的主键和外键
- 两个栈实现队列
- 001_UNIX发展历史和发行版本
- redis系列(二)数据结构
- tf常见疑惑
- thuwc2017滚粗记
- 计算机网络面试题总结
- 【译】走近人工智能
- HDU 1846 Brave Game(简单巴什博弈)
- 003_过滤和排序数据