使用两个栈构建一个队列
2014-06-30 00:00
246 查看
摘要: 使用两个栈构建一个队列
题目
使用两个栈构建一个队列分析
很老的问题,思路使用一个主栈接收输入, 另一个作辅助栈弹出数据,而由主栈到辅助栈的数据转移完成栈数据转化为队列顺序代码
#include <stack> #include <iostream> #include <cstdio> using namespace std; class Squeue{ public: Squeue(void) { squeueDestory(); } ~Squeue(void) { squeueDestory(); } void push(const int &val){ stackMaster.push(val); } int pop(void){ int val; if(stackServant.empty()){ servantCharge(); } if(stackServant.empty()){ return -1; } val = stackServant.top(); stackServant.pop(); return val; } private: void servantCharge(void){ while(!stackMaster.empty()){ int val; val = stackMaster.top(); stackServant.push(val); stackMaster.pop(); } } void squeueDestory(void){ while(!stackServant.empty()){ stackServant.pop(); } while(!stackMaster.empty()){ stackMaster.pop(); } } stack<int> stackMaster; stack<int> stackServant; }; #define PUSH "PUSH" #define POP "POP" int main(int argc, char *argv[]){ string action; int val; int actionCnt; int actionTot; class Squeue sq; cin >> actionTot; for(actionCnt = 1; actionCnt <= actionTot; actionCnt++){ cin >> action; if(action == PUSH){ cin >> val; sq.push(val); }else if(action == POP){ cout << sq.pop() << endl; }else{ cout << "assert" << endl; return -1; } } return 0; }
相关文章推荐
- 使用两个Stack类(JDK容器类库中的Stack类)实现一个队列类MyQueue,提供队列的入队列和出队列操作:enQueue和deQueue
- cc150:使用两个栈实现一个队列(两种方法比较)
- 【数据结构】(面试题)使用两个栈实现一个队列(详细介绍)
- 使用两个栈来实现一个队列简单的push和pop
- 使用两个栈实现一个队列
- 使用两个队列实现一个栈,使用两个栈实现一个队列!
- 【数据结构】(面试题)使用两个栈实现一个队列(详细介绍)
- 使用两个队列实现一个栈
- 使用两个栈实现一个队列
- 使用两个栈实现一个队列
- 013使用两个栈实现一个队列(keep it up)
- 使用两个队列实现一个栈
- 剑指 | 7-利用两个栈构建一个队列
- 使用两个栈实现一个队列
- 使用两个队列实现一个栈,使用两个栈实现一个队列!
- 使用两个队列实现一个栈
- 使用两个栈实现一个队列
- 使用两个栈实现一个队列
- 使用两个栈模拟一个队列【C语言】
- 使用两个栈实现一个队列