AcWing 20. 用两个栈实现队列
原题链接
简单
作者:
满地王八我壳最绿.
,
2023-12-03 16:54:08
,
所有人可见
,
阅读 42
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> sinput; //输入栈,负责输入数据和向输出栈中导入数据
stack<int> soutput; //输出栈,负责取队头元素和出队操作
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
sinput.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(!soutput.empty()){
int t = soutput.top();
soutput.pop();
return t;
}
while(!sinput.empty()){
soutput.push(sinput.top());
sinput.pop();
}
int t = soutput.top();
soutput.pop();
return t;
}
/** Get the front element. */
int peek() {
if(!soutput.empty()) return soutput.top();
while(!sinput.empty()){
soutput.push(sinput.top());
sinput.pop();
}
return soutput.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return sinput.empty() && soutput.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();
*/