AcWing 20. 用两个栈实现队列
原题链接
简单
看了N次Y总视频,终于过了😁😊
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> x1,y1;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
x1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
while(x1.size()>1)y1.push(x1.top()),x1.pop();
int s=x1.top();
x1.pop();
while(y1.size())x1.push(y1.top()),y1.pop();
return s;
}
/** Get the front element. */
int peek() {
while(x1.size()>1)y1.push(x1.top()),x1.pop();
int s=x1.top();
while(y1.size())x1.push(y1.top()),y1.pop();
return s;
}
/** Returns whether the queue is empty. */
bool empty() {
if(x1.size()) 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();
*/