解法一:双栈法
用一个栈来保存栈的顺序,一个栈来保存相反的顺序即队列的顺序;两个栈相互颠倒,就可以操作头部和尾部了。
class MyQueue {
private:
stack<int> s1; //队列顺序的内容 平时数据存放在队列顺序的栈中
stack<int> s2; //栈顺序的内容
public:
/** Initialize your data structure here. */
MyQueue() { }
void push(int x) { //入队
while(!s1.empty()){ //将队列顺序内容以栈顺序进入s2
s2.push(s1.top());
s1.pop();
}
s2.push(x); //将x压入栈顺序存储的s2
while(!s2.empty()){ //将栈顺序的内容s2,以队列顺序压入s1
s1.push(s2.top());
s2.pop();
}
}
int pop() { //出队
int res=s1.top();
s1.pop();
return res;
}
int peek() { //获取队首
return s1.top();
}
bool empty() { //队空
if(s1.empty())
return true;
else
return false;
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/