AcWing 20. 用两个栈实现队列
原题链接
简单
作者:
跟着灿哥学切菜
,
2021-01-28 21:11:49
,
所有人可见
,
阅读 429
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);
}
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 res = cache.top();
cache.pop();
copy(cache, stk);
return res;
}
/** Get the front element. */
int peek() {
copy(stk, cache);
int res = cache.top();
copy(cache, stk);
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return stk.size() == 0;
}
};
/**
* 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();
*/