-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue.java
87 lines (71 loc) · 1.34 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
public class Queue<AnyType> {
public static void main(String[] args) {
Queue<Integer> ints = new Queue<Integer>();
ints.printQueue();
ints.enqueue(4);
ints.enqueue(5);
ints.enqueue(6);
ints.printQueue();
ints.dequeue();
ints.printQueue();
ints.dequeue();
ints.printQueue();
ints.dequeue();
ints.printQueue();
ints.enqueue(4);
ints.enqueue(5);
ints.enqueue(6);
ints.printQueue();
}
private class Node {
AnyType data;
Node next;
Node(AnyType data, Node next) {
this.data = data;
this.next = next;
}
}
private Node head;
private Node tail;
private int size;
public Queue() {
this.head = null;
this.tail = null;
size = 0;
}
public int size() {
return size;
}
public boolean empty() {
return size() == 0;
}
public void enqueue(AnyType item) {
Node newNode = new Node(item, null);
if (empty()) {
head = newNode;
} else {
tail.next = newNode;
}
tail = newNode;
size++;
}
public AnyType dequeue() {
if (empty()) {
throw new IndexOutOfBoundsException();
}
AnyType item = head.data;
head = head.next;
size--;
return item;
}
public void printQueue() {
Node node = head;
// System.out.println("head->");
while (node != null) {
System.out.print(node.data + "->");
node = node.next;
}
System.out.println("null");
// System.out.println("<-tail");
}
}