程序员面试题:如何用栈实现队列?如果用数组实现呢?

By LongLuo

Leetcode232. 用栈实现队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class MyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;

public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}

public void push(int x) {
if (stack1.empty()) {
stack1.push(x);
return;
}

while (!stack1.empty()) {
stack2.push(stack1.pop());
}
stack2.push(x);
while (!stack2.empty()) {
stack1.push(stack2.pop());
}
}

public int pop() {
return stack1.pop();
}

public int peek() {
return stack1.peek();
}

public boolean empty() {
return stack1.empty() && stack2.empty();
}
}

用数组实现队列: