用两个栈实现队列 【C++实现】
来源:互联网 发布:网络主播瞳孔 编辑:程序博客网 时间:2024/06/01 08:46
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
给定函数头
class Solution{public: void push(int node) { } int pop() { }private: stack<int> stack1; stack<int> stack2;};
思路:
在执行push时,令stack2为空,将待存元素压入stack1的栈顶;
在执行pop时,令stack1为空,stack2的栈顶元素即为待pop元素;
用容器实现起来特别简单。
代码
class Solution{public://stack1用于存储,stack2用于临时存储stack1的元素,以完成出队void push(int node) {while (!stack2.empty()) { //执行push时,令stack2为空,将待存元素压入stack1的栈顶;stack1.push(stack2.top());stack2.pop();}stack1.push(node);}int pop() {while(!stack1.empty()) { //执行pop时,令stack1为空,stack2的栈顶元素即为待pop元素;stack2.push(stack1.top());stack1.pop();}int temp = stack2.top();//取出stack2栈顶元素,存入临时变量temp,待返回。stack2.pop(); //别忘了销毁哦return temp;}private:stack<int> stack1;stack<int> stack2;};
阅读全文
0 0
- 两个栈实现一个队列(C/C++)
- 用两个栈实现队列 & 用两个队列实现栈
- 用两个队列实现栈&用两个栈实现队列
- 用两个栈实现队列 & 两个队列实现一个栈
- 两个栈实现队列&&用两个队列实现一个栈
- 用两个栈实现队列 & 两个队列实现栈
- C++:利用两个栈实现队列操作
- 【C++】两个队列实现一个栈
- 【C++】两个栈实现一个队列
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个队列实现栈
- 京东-首页轮播
- Oculus 揭秘 VR 中的近场 3D 音效技术
- bzoj 1641: Cow Hurdles 奶牛跨栏 floyd
- Java加密技术(四)——非对称加密算法RSA
- C语言实现扫雷游戏
- 用两个栈实现队列 【C++实现】
- 线程初步(一)
- The C Programming Language 练习题2-6
- 160个练手CrackMe-002
- windows批处理命令教程
- Error creating bean with name 'diaryDAO' defined in class path resource [applicationContext.xml]:
- 远程主机执行命令
- Hive的产生背景 & 概述 & 发展历程 & 架构 & 部署及简单入门
- python数据分析中的时间处理(2)