-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedQueue.java
96 lines (81 loc) · 2.27 KB
/
LinkedQueue.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
public class LinkedQueue<T> implements QueueInterface<T>{
private Node firstNode; // node at the end of the queue
private Node lastNode; // node at the front of the queue
public LinkedQueue(){
this.firstNode = null;
this.lastNode = null;
} // end constructor
private class Node {
private T data;
private Node next;
private Node (T data, Node next){
this.data = data;
this.next = next;
} // end constructor
// mutators/accessors
public T getData(){
return this.data;
}
public void setData(T data){
this.data = data;
}
public Node getNext(){
return this.next;
}
public void setNext(Node next){
this.next = next;
}
} // end Node class
/**
* adds a specified entry to the back of the queue
* @param newEntry an object to be added
*/
public void enqueue(T newEntry){
Node newNode = new Node(newEntry, null);
if (isEmpty()){
firstNode = newNode;
}
else {
lastNode.setNext(newNode);
}
lastNode = newNode;
}
/**
* retrieves the entry at the front of a non-empty queue
* @return the object at the front of the queue
*/
public T getFront(){
if (isEmpty()){
throw new EmptyQueueException();
}
else {
return firstNode.getData();
}
}
/**
* retrives and removes the entry at the front of a non-empty queue
* @return the object at the front of the queue
*/
public T dequeue(){
T front = getFront(); // might throw exception, assumes firstNode != null
firstNode = firstNode.getNext();
if (firstNode == null){
lastNode = null;
} // end if
return front;
} // end dequeue
/**
* detects whether the queue is empty
* @return true if the queue is empty, false otherwise
*/
public boolean isEmpty(){
return firstNode == null;
} // end isEmpty
/**
* removes all entries from the queue
*/
public void clear(){
firstNode = null;
lastNode = null;
} // end clear
} // end LinkedQueue