-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueue.java
88 lines (78 loc) · 1.98 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<T>
{
// Here generics are used to make sure the containers, i.e. the Node
// is the same type as the data it holds.
// These are also object references which constantly change. They are used to
// hold the particular objects of interes namely the start and the end of the queue.
Node<T> start;
Node<T> end;
public Queue()
{
start = null;
end = null;
}
// Again generic type is used for the actual data to be stored in the queue.
public void add(T item)
{
Node<T> n = new Node<>(item);
// No items.
if(end == null)
{
start = n;
end = n;
}
else
{
end.next = n;
// Again the object reference used has to be updated
// in order to point to the right object.
end = n;
}
}
// Here generic type is used for the return type.
public T remove()
{
if(start == null)
return null;
else
{
T toReturn = start.item;
if(start == end)
{
start = null;
end = null;
}
else
start = start.next;
return toReturn;
}
}
public boolean contains(T item)
{
// A nice example of object references...
// A current node to keep track of the current Node,
// while the queue is being traversed.
Node<T> current = start;
while(current != null)
{
if(current.item.equals(item))
{
return true;
}
// Object refere update.
current = current.next;
}
return false;
}
// Private inner class.
private class Node<S>
{
private S item;
private Node<S> next;
public Node(S data)
{
item = data;
next = null;
}
}
}