- 每次push,都push到stack1
- 每次pop,如果stack2为空,就把stack1中的所有元素“倒入”stack2,这样就使得最先进入stack1的元素又回到了栈顶
class MyQueue {
public:
stack<int> stack1;
stack<int> stack2;
MyQueue() {
// do intialization if necessary
stack1 = stack<int>();
stack2 = stack<int>();
}
void push(int element) {
// write your code here
stack1.push(element);
}
int pop() {
// write your code here
int pop_elem = top();
stack2.pop();
return pop_elem;
}
int top() {
// write your code here
if (stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.top());
stack1.pop();
}
}
return stack2.top();
}
};