AcWing 20. 用两个栈实现队列
原题链接
简单
作者:
adamXu
,
2020-09-24 09:23:26
,
所有人可见
,
阅读 283
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> stk,cache;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stk.push(x);
}
//将a中的元素逆序放到b中,结束后a为空
void copy(stack<int> &a,stack<int> &b){
while(a.size()){
b.push(a.top());
a.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
copy(stk,cache);
int x = cache.top();
cache.pop();
copy(cache,stk);
return x;
}
/** Get the front element. */
int peek() {
copy(stk,cache);
int x = cache.top();
copy(cache,stk);
return x;
}
/** Returns whether the queue is empty. */
bool empty() {
return stk.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();
*/