-
-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathMyQueue.java
More file actions
41 lines (34 loc) · 843 Bytes
/
Copy pathMyQueue.java
File metadata and controls
41 lines (34 loc) · 843 Bytes
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
package leetcode.easy;
import java.util.Stack;
public class MyQueue {
private final Stack<Integer> input;
private final Stack<Integer> output;
public MyQueue() {
input = new Stack<>();
output = new Stack<>();
}
public void push(int x) {
input.push(x);
}
public int pop() {
peek();
return output.pop();
}
public int peek() {
if (output.empty())
while (!input.empty())
output.push(input.pop());
return output.peek();
}
public boolean empty() {
return input.empty() && output.empty();
}
public static void main(String[] args) {
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
System.out.println(queue.peek()); // returns 1
System.out.println(queue.pop()); // returns 1
System.out.println(queue.empty()); // returns false
}
}