用两个栈实现队列
2016-03-23 17:23
369 查看
题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。
队列中的元素为int类型。
算法实现:
思想:将两个栈(我们这里称做stack1, stack2)。stack1用作push操作,stack2用作pop操作。我们知道队列是先进先出,所以如果有数据进队列,将数据压入stack1中,如果需要输出数据,先将stack1中的数据弹出同时压入stack2中,此时先进入stack1中的数据会在stack2中的栈顶,弹出即可。正好实现了队列的功能。
用两个栈来实现一个队列,完成队列的Push和Pop操作。
队列中的元素为int类型。
算法实现:
#include<iostream> #include<stack> #include<string> using namespace std; stack<int> stack1; stack<int> stack2; void Push(const int &node){ //对stack1进行push操作 stack1.push(node); } int Pop(){ //将stack2进行pop操作 if(stack2.size() <= 0){ while(stack1.size() > 0){ int &data = stack1.top(); stack1.pop(); stack2.push(data); } } if(stack2.size() == 0){ return -1; } int head = stack2.top(); stack2.pop(); return head; } int main(){ long num; string str; cin >> num; while(num-- > 0){ cin>>str; if(str == "PUSH"){ int x; cin>>x; Push(x); } else if(str == "POP"){ int ls = Pop(); if(ls < 0){ cout<<"-1"<<endl; }else{ cout<<ls<<endl; } } } return 0; }
思想:将两个栈(我们这里称做stack1, stack2)。stack1用作push操作,stack2用作pop操作。我们知道队列是先进先出,所以如果有数据进队列,将数据压入stack1中,如果需要输出数据,先将stack1中的数据弹出同时压入stack2中,此时先进入stack1中的数据会在stack2中的栈顶,弹出即可。正好实现了队列的功能。
相关文章推荐
- 基于ZigBee和STM32的智能家居控制系统的设计与实现(收藏)
- 广播与服务二
- action 提示框
- 后台页面相同模块(导航条等)的处理
- HTML5新增结构标签
- C内存分配方式与C++内存分配方式
- jquery如何判断滚动条滚到页面底部并执行事件
- 解决方案: scp/ssh 的登陆提示很慢 (Linux)
- task4: 结对编程-词频统计[修改版]
- Elasticsearch aggregations 理解
- ubuntu 格式化U盘,并制作系统镜像
- blas
- Glide 入门到精通之九——SimpleTarget 和 ViewTarget 用于自定义视图类
- Android中ListView.getCount()与ListView.getChildCount()区别
- The Smallest String Concatenation 一道让自己崩溃的题
- Exel表格文件上传
- SpringMVC返回json数据的配置方式
- Flat - Music scores and guitar tabs editor(乐谱编辑器)
- HDOJ 2029 Palindromes _easy version
- SlidingMenu侧滑菜单栏