Repository navigation
Expand file tree
/
Copy path0232. Implement Queue using Stacks.java
More file actions
86 lines (70 loc) · 1.74 KB
/
Copy path0232. Implement Queue using Stacks.java
File metadata and controls
86 lines (70 loc) · 1.74 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// class MyQueue {
// private Stack<Integer> stack;
// private Stack<Integer> stack2;
// public MyQueue() {
// stack = new Stack<>();
// stack2 = new Stack<>();
// }
// public void push(int x) {
// stack.push(x);
// }
// public int pop() {
// check();
// return stack2.pop();
// }
// public int peek() {
// check();
// return stack2.peek();
// }
// public boolean empty() {
// return stack.isEmpty() && stack2.isEmpty();
// }
// public void check() {
// if (stack2.isEmpty()) {
// while (!stack.isEmpty()) {
// stack2.push(stack.pop());
// }
// }
// }
// }
// /**
// * Your MyQueue object will be instantiated and called as such:
// * MyQueue obj = new MyQueue();
// * obj.push(x);
// * int param_2 = obj.pop();
// * int param_3 = obj.peek();
// * boolean param_4 = obj.empty();
// */
class MyQueue {
private Deque<Integer> in = new ArrayDeque<>();
private Deque<Integer> out = new ArrayDeque<>();
public void push(int x) {
in.push(x);
}
public int pop() {
moveIfNeeded();
return out.pop();
}
public int peek() {
moveIfNeeded();
return out.peek();
}
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
private void moveIfNeeded() {
if (out.isEmpty()) {
while (!in.isEmpty()) {
out.push(in.pop());
}
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/