We recall first the Queue interface shown in Figure 4.2.
public interface Queue {
public boolean isEmpty();
public void enqueue(Object item);
public Object dequeue();
}
|
For efficiency, we need to keep track of the last item in the queue, assuming there is one. This will be referred to by the variable back as shown in the diagram.
The code for the linked list implementation of the Queue interface is shown in Figure 4.3.
import java.util.NoSuchElementException;
public class QueueList implements Queue {
private ListNode front;
private ListNode back;
public QueueList() {
front = null;
}
public boolean isEmpty() {
return front == null;
}
public void enqueue(Object item) {
if (front == null) {
front = back = new ListNode(item, null);
} else {
back = back.next = new ListNode(item, null);
}
}
public Object dequeue() {
if (front == null) {
throw new NoSuchElementException();
} else {
Object item = front.data;
front = front.next;
return item;
}
}
}
|
Note that back refers to the last element of the list if
the list is non-empty. If the list is empty, meaning that
front = null, then back may refer anywhere. But if the
list is empty, no use can be made of the current reference of back, so its value is not significant.