题目:
https://www.acwing.com/problem/content/description/36/
Tips:
不需要重复在两个栈之间搬运
代码:
class MyQueue {
public:
stack<int> s1, s2;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
s1.push(x);
}
void move()
{
while (!s1.empty())
{
int t = s1.top();
s1.pop();
s2.push(t);
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if (s2.empty())
move();
int t = s2.top();
s2.pop();
return t;
}
/** Get the front element. */
int peek() {
if (s2.empty())
move();
return s2.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return (s1.empty() && s2.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();
*/