AcWing 20. 用两个栈实现队列
原题链接
简单
作者:
米多奇香米饼
,
2023-01-23 11:25:58
,
所有人可见
,
阅读 121
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);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
//将stk中的元素倒着装到cache中
while(stk.size()){
cache.push(stk.top());
stk.pop();
}
//取到cache中最上层的元素(stk中最底层的元素)
int res=cache.top();
//将此元素从栈中清除
cache.pop();
//将cache中的元素倒着装到stk中
while(cache.size()){
stk.push(cache.top());
cache.pop();
}
return res;
}
/** Get the front element. */
int peek() {
//将stk中的元素倒着装到cache中
while(stk.size()){
cache.push(stk.top());
stk.pop();
}
//取到cache中最上层的元素(stk中最底层的元素)
int res=cache.top();
//将cache中的元素倒着装到stk中
while(cache.size()){
stk.push(cache.top());
cache.pop();
}
return res;
}
/** 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();
*/