两个栈实现队列
解题思路:
进队列时,将元素压入栈Stack1
出队列时,将栈Stack1中的元素出栈压进Stack2中,当栈Stack1剩余一个元素时,将栈Stack1的元素pop
最后将栈Stack2的元素一个个的压入栈Stack1中
取队顶元素时,输出要pop的元素
取队尾元素时,直接取栈顶元素
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
class Stackqueue{
stack<int> Stack1;
stack<int> Stack2;
public:
void push(int x){
Stack1.push(x);
}
void pop(){
while (Stack1.size() > 1){
Stack2.push(Stack1.top());
Stack1.pop();
}
Stack1.pop();
while (!Stack2.empty()){
Stack1.push(Stack2.top());
Stack2.pop();
}
}
int back(){
return Stack1.top();
}
int front(){
while (!Stack1.empty()){
Stack2.push(Stack1.top());
Stack1.pop();
}
int tmp = Stack2.top();
while (!Stack2.empty()){
Stack1.push(Stack2.top());
Stack2.pop();
}
return tmp;
}
};
int main(){
Stackqueue sq;
sq.push(1);
sq.push(2);
sq.push(3);
sq.push(4);
cout << sq.front() << endl;
sq.pop();
cout << sq.front() << endl;
sq.pop();
cout << sq.front() << endl;
sq.pop();
cout << sq.front() << endl;
sq.pop();
system("pause");
return 0;
}