-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedQueue.java
More file actions
102 lines (91 loc) · 2.42 KB
/
Copy pathLinkedQueue.java
File metadata and controls
102 lines (91 loc) · 2.42 KB
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
public class LinkedQueue<T> implements QueueADT<T> {
private int count;
private LinearNode<T> front, rear;
/**
* Creates an empty queue.
*/
public LinkedQueue(){
count = 0;
front = rear = null;
}
/**
* Adds the specified element to the rear of this queue.
*
* @param element the element to be added to the rear of this queue
*/
public void enqueue(T element){
LinearNode<T> node = new LinearNode<T>(element);
if (isEmpty()){
front = node;
}else{
rear.setNext (node);
}
rear = node;
count++;
}
/**
* Removes the element at the front of this queue and returns a
* reference to it. Throws an EmptyCollectionException if the
* queue is empty.
*
* @return the element at the front of this queue
* @throws EmptyCollectionException if an empty collection exception occurs
*/
public T dequeue() throws EmptyCollectionException{
if (isEmpty()){
throw new EmptyCollectionException ("queue");
}
T result = front.getElement();
front = front.getNext();
count--;
if (isEmpty()){
rear = null;
}
return result;
}
/**
* Returns a reference to the element at the front of this queue.
* The element is not removed from the queue. Throws an
* EmptyCollectionException if the queue is empty.
*
* @return a reference to the first element in
* this queue
* @throws EmptyCollectionsException if an empty collection exception occurs
*/
public T first() throws EmptyCollectionException{
if (isEmpty()){
throw new EmptyCollectionException ("queue");
}
return front.getElement();
}
/**
* Returns true if this queue is empty and false otherwise.
*
* @return true if this queue is empty and false if otherwise
*/
public boolean isEmpty(){
return (count == 0);
}
/**
* Returns the number of elements currently in this queue.
*
* @return the integer representation of the size of this queue
*/
public int size(){
return count;
}
/**
* Returns a string representation of this queue.
*
* @return the string representation of this queue
*/
public String toString(){
String result = "";
LinearNode<T> current = front;
while (current != null){
result = result + (current.getElement()).toString() + "\n";
current = current.getNext();
}
return result;
}
}