- 需要取第一个压入栈的元素时,将第一个栈的元素全倒入第二个栈,第二个栈中越靠近栈顶的就是越早入栈的元素。后续只需要取第二个栈元素,直到第二个栈为空时,再将第一个栈的元素全倒入第二个栈
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {}
/** Push element x to the back of queue. */
void push(int x) { a.emplace(x); }
/** Removes the element from in front of queue and returns that element. */
int pop() {
if (std::empty(b)) {
while (!std::empty(a)) {
int t = a.top();
a.pop();
b.emplace(t);
}
}
int res = b.top();
b.pop();
return res;
}
/** Get the front element. */
int peek() {
if (std::empty(b)) {
while (!std::empty(a)) {
int t = a.top();
a.pop();
b.emplace(t);
}
}
return b.top();
}
/** Returns whether the queue is empty. */
bool empty() { return std::empty(a) && std::empty(b); }
private:
stack<int> a;
stack<int> b;
};