使用第一个栈存储push的元素,只有当需要pop时,才将第二个栈中的元素全部倒入到第二个栈中。n次操作总复杂度为O(n)
class MyQueue {
private:
stack<int> st1,st2;
int popSt2(){
int ans=st2.top();
st2.pop();
return ans;
}
void transfer(){
while(!st1.empty()){
st2.push(st1.top());
st1.pop();
}
}
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
st1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(!st2.empty()){
return popSt2();
}
transfer();
return popSt2();
}
/** Get the front element. */
int peek() {
if(!st2.empty()){
return st2.top();
}
transfer();
return st2.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return st1.empty() && st2.empty();
}
};