-
Notifications
You must be signed in to change notification settings - Fork 28
/
Queue.java
103 lines (78 loc) · 1.63 KB
/
Queue.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
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package ds_004_stacks_and_queues;
public class Queue<T> {
private final Node<T> head;
private final Node<T> tail;
private int size;
public Queue() {
head = new Node<T>(null);
tail = new Node<T>(null);
head.next = tail;
tail.prev = head;
size = 0;
}
public void enqueue(T value) {
Node<T> newNode = new Node<>(value);
newNode.next = head.next;
newNode.prev = head;
head.next.prev = newNode;
head.next = newNode;
size++;
}
/*
* ...... -> prev -> last -> tail
*/
public T dequeue() {
if(tail.prev == null) {
return null;
}
Node<T> last = tail.prev;
last.prev.next = tail;
tail.prev = last.prev;
T value = last.value;
last = null;
size--;
return value;
}
public T peek() {
if(isEmpty()) {
return null;
}
return head.next.value;
}
// trivial methods
public boolean isEmpty() {
return size == 0 ? true : false;
}
public int size() {
return size;
}
public void print() {
System.out.print("Stack: ");
if(size == 0) {
System.out.print("EMPTY");
} else {
for(Node<T> curr = head.next; curr != tail; curr = curr.next) {
System.out.printf("%s " , curr.value);
}
}
System.out.print("\n");
}
public void state() {
System.out.println("State;");
System.out.println("\tIsEmpty: " + isEmpty());
System.out.println("\tSize : " + size);
}
/*
* static nested class
* we don't need any reference to parent class
*/
private static class Node<T> {
public final T value;
public Node<T> prev;
public Node<T> next;
public Node(final T value) {
this.value = value;
this.prev = this.next = null;
}
}
}