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