40. Implement Queue by Two Stacks【medium】

时间:2023-03-08 23:27:07
40. Implement Queue by Two Stacks【medium】

As the title described, you should only use two stacks to implement a queue's actions.

The queue should support push(element), pop() and top() where pop is pop the first(a.k.a front) element in the queue.

Both pop and top methods should return the value of first element.

Example
push(1)
pop() // return 1
push(2)
push(3)
top() // return 2
pop() // return 2
Challenge

implement it by two stacks, do not use any other data structure and push, pop and top should be O(1) by AVERAGE.

解法一:

 class MyQueue {
public:
stack<int> stack1;
stack<int> stack2; MyQueue() {
} void push(int element) {
stack1.push(element);
} void adjust() {
if (stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.top());
stack1.pop();
}
}
} int pop() {
adjust();
int temp = stack2.top();
stack2.pop();
return temp;
} int top() {
adjust();
return stack2.top();
}
};