您的位置:首页 > 其它

用两个栈实现队列

2016-03-23 17:23 369 查看
题目描述:

用两个栈来实现一个队列,完成队列的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中的栈顶,弹出即可。正好实现了队列的功能。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: