用两个队列实现栈
首先用两个队列模拟栈,两个队列是输入队列InputQueue和输出队列OutputQueue。
- -push:直接将输入的数据压入InputQueue.
- -pop:假设InputQueue有N个数据,将N-1个数据压入OutputQueue,将InputQueue中的最后一个数据弹出,并将InputQueue执行pop操作,清空队列,执行pop操作。执行完成之后将OutputQueue中的数据重新压入InputQueue中。
- -top:假设InputQueue有N个数据,将N-1个数据压入OutputQueue,将InputQueue中的最后一个数据返回,执行top操作,将最后一个数据重新压入OutputQueue,并将InputQueue执行pop操作,清空队列。执行完成之后将OutputQueue中的数据重新压入InputQueue中。
#include<queue>
#include<iostream>
using namespace std;
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {}
/** Push element x to the back of queue. */
void push(int x) {
InputQueue.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
while (InputQueue.size() != 1)
{
OutputQueue.push(InputQueue.front());
InputQueue.pop();
}
int top = InputQueue.front();
InputQueue.pop();
while (!OutputQueue.empty())
{
InputQueue.push(OutputQueue.front());
OutputQueue.pop();
}
return top;
}
/** Get the front element. */
int top() {
while (InputQueue.size() != 1)
{
OutputQueue.push(InputQueue.front());
InputQueue.pop();
}
int top = InputQueue.front();
InputQueue.pop();
OutputQueue.push(top);
while (!OutputQueue.empty())
{
InputQueue.push(OutputQueue.front());
OutputQueue.pop();
}
return top;
}
/** Returns whether the queue is empty. */
bool empty() {
if (OutputQueue.empty() && InputQueue.empty())
return true;
return false;
}
private:
queue<int> InputQueue;
queue<int> OutputQueue;
};
int main()
{
MyStack stk;
stk.push(1);
stk.push(2);
cout<< stk.top() << endl;
cout << stk.pop() << endl;
}