AcWing 20. 用两个栈实现队列
原题链接
简单
作者:
Value
,
2020-08-27 11:53:13
,
所有人可见
,
阅读 376
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> stk1, stk2;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
while(!stk1.empty()){
int p = stk1.top();
stk1.pop();
stk2.push(p);
}
stk1.push(x);
while(!stk2.empty()){
int p = stk2.top();
stk2.pop();
stk1.push(p);
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int res = stk1.top();
stk1.pop();
return res;
}
/** Get the front element. */
int peek() {
return stk1.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return stk1.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();
*/