next up previous index
Next: Comparison Up: Linked Implementations Previous: List Implementation of Stack   Index


List Implementation of Queue

We recall first the Queue interface shown in Figure 4.2.

Figure 4.2: An interface for the Queue abstract data type.
public interface Queue {
    public boolean isEmpty();
    public void enqueue(Object item);
    public Object dequeue();
}

Implementation of queues using lists is very similar to the implementation of stacks, except that in this case items join the queue at the back and leave at the front. If the queue is represented by the list [5, 2], adding a new item 3 will give the list [5, 2, 3]. In other words new items are added to the end of the list. Removing an item from the queue is the same as for stacks. It comes off the front.

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.


\begin{picture}(440,95)
\put(50,32){\makebox(0,0){\tt front}}
\put(20,20){\vec...
...(300,90){\makebox(0,0){\tt back}}
\put(300,80){\vector(1,-2){20}}
\end{picture}

The code for the linked list implementation of the Queue interface is shown in Figure 4.3.

Figure 4.3: A list implementation of the Queue interface.
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; 
        }
    }
}

The code for dequeue is the same as the pop method for stacks. The enqueue method needs to check first whether or not the list is empty. In that case a new node is created and the front and back are the same. If the list is not empty, a new node is added at the back of the old list, and this becomes the back of the new list.

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.


next up previous index
Next: Comparison Up: Linked Implementations Previous: List Implementation of Stack   Index
Peter Williams 2005-06-07