p232

LeetCode p232 Implement Queue using Stacks 题解

1.题目:

Implement the following operations of a queue using stacks.

push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.

题意:

用栈实现队列

2.解题思路:

见代码,两个栈。

3.代码


[title] [] [url] [link text]
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
37
38
39
40
41
 
class MyQueue {
// Push element x to the back of queue.
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();

public void push(int x) {
stack2.add(x);
}

// Removes the element from in front of queue.
public void pop() {
if (stack1.empty()) {
while (!stack2.empty()){
// 移除
stack1.add(stack2.pop());
}
stack1.pop();
} else {
stack1.pop();
}
}

// Get the front element.
public int peek() {
if (stack1.empty()) {
while (!stack2.empty()){
// 移除
stack1.add(stack2.pop());
}
return stack1.peek();
} else {
return stack1.peek();
}
}

// Return whether the queue is empty.
public boolean empty() {
return stack1.empty() && stack2.empty();
}
}

4.一些总结: