AcWing 20. 用两个栈实现队列
原题链接
简单
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> x,y;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int xx) {
x.push(xx);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
while (!x.empty()) y.push(x.top()),x.pop();
int res=y.top();y.pop();
while (!y.empty()) x.push(y.top()),y.pop();
return res;
}
/** Get the front element. */
int peek() {
while (!x.empty()) y.push(x.top()),x.pop();
int res=y.top();
while (!y.empty()) x.push(y.top()),y.pop();
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return x.empty()&&y.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* bool param_4 = obj.empty();
*/