您的位置:首页 > 其它

使用两个栈构建一个队列

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: