两个栈实现队列
来源:互联网 发布:linux编写shell程序 编辑:程序博客网 时间:2024/06/05 04:05
问题描述:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
函数接口:void push(int node)
int pop()
解题方法:首先对于实现队列push的方法只需要将元素放入stack1中就可以了,对于队列pop的方法,首先判断stack2是否为空,如果为空直接将stack1中的所有元素全部弹出栈并且压入stack2中,然后将stack2栈顶元素弹出,如果stack2不为空,则直接将stack2中的栈顶元素弹出就可以了。
算法代码:
void push(int node) //进队列 { stack1.push(node); } int pop() //出队列 { int elem = 0; if (stack2.empty())//判断stack2是否为空 { while (!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } } elem=stack2.top(); stack2.pop(); return elem; }
下面给出所有代码和测试结果
#include<iostream>#include<stack>using namespace std;class Solution{public: void push(int node) //进队列 { stack1.push(node); } int pop() //出队列 { int elem = 0; if (stack2.empty())//判断stack2是否为空 { while (!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } } elem=stack2.top(); stack2.pop(); return elem; }private: stack<int> stack1; stack<int> stack2;};int main(){ Solution s; s.push(1); s.push(2); cout << s.pop(); cout << s.pop(); s.push(1); s.push(2); s.push(3); cout << s.pop(); cout << s.pop(); cout << s.pop(); system("pause"); return 0;}
测试结果如下:正确应该按照队列先进先出的顺序输出12123
这道题比较简单在《栈和队列的相关面试题》中我也写过,想看关于栈和队列一些问题的可以点击下面查看
栈和队列的面试题
阅读全文
0 0
- 两个栈实现队列
- 两个队列实现栈
- 两个栈实现队列
- 两个栈实现队列
- 两个栈实现队列
- 两个队列实现栈
- 两个栈实现队列
- 两个 栈 实现队列
- 两个栈实现队列
- 两个队列实现栈
- 两个栈实现队列
- 两个栈实现队列
- 两个队列实现栈
- 两个栈实现队列
- 两个栈实现队列
- 两个栈实现队列
- 队列--两个栈实现
- 两个队列实现栈
- mui 子页面回传值到父页面
- 训练日记
- mysql 在不同数据库中创建定时同步任务,将每分钟数据转每5分钟统计
- display属性
- JAVA之 方法调用
- 两个栈实现队列
- 第十四周 项目二 用哈希法组织关键字(1)线性探测法处理冲突
- Zotero查看文献条目所属的分类
- C语言基础(四)(指针)
- C++学习笔记--抽象类-纯虚函数
- 动态规划—0-1背包
- CentOS6上安装redis并配置服务自启动
- MTD(2)---nand flash的底层驱动代码分析
- 文件隐藏