/
MyQueue.java
44 lines (37 loc) · 1.02 KB
/
MyQueue.java
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
import java.util.Stack;
public class MyQueue {
private Stack<Integer> head = new Stack<Integer>();
private Stack<Integer> tail = new Stack<Integer>();
// Push element x to the back of queue.
public void push(int x) {
tail.push(x);
}
// Removes the element from in front of queue.
public void pop() {
if (head.isEmpty()) {
while (!tail.isEmpty()) {
head.push(tail.pop());
}
}
head.pop();
}
// Get the front element.
public int peek() {
if (head.isEmpty()) {
while (!tail.isEmpty()) {
head.push(tail.pop());
}
}
return head.peek();
}
// Return whether the queue is empty.
public boolean empty() {
return head.isEmpty() && tail.isEmpty();
}
public static void main(String[] args) {
MyQueue queue = new MyQueue();
queue.push(2);
queue.push(3);
System.out.println(queue.peek());
}
}