-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyQueue.java
More file actions
56 lines (46 loc) · 1.04 KB
/
Copy pathMyQueue.java
File metadata and controls
56 lines (46 loc) · 1.04 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package leetcode.easy.page2;
import java.util.Stack;
/**
* @author Kyle
* @create 2018/9/24 10:01
*/
public class MyQueue {
private Stack<Integer> a, b;
/** Initialize your data structure here. */
public MyQueue() {
a = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
a.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
move();
int res = a.pop();
recover();
return res;
}
/** Get the front element. */
public int peek() {
move();
int res = a.peek();
recover();
return res;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return a.isEmpty();
}
private void move() {
b = new Stack<>();
while (a.size() > 1) {
b.push(a.pop());
}
}
private void recover() {
while (b.size() > 0) {
a.push(b.pop());
}
}
}