Worksheet 18: Linked List Queue, pointer to Tail
In Preparation: Read Chapters 6 and 7 to learn more about the Stack and Queue data
types. If you have not done so already, you should do Lesson 17 to learn about the basic
features of a linked list.
One problem with the linked list stack is that it only permits rapid access to the front of
the collection. This was no problem for the stack operations described in Lesson 17, but
would present a difficulty if we tried to implement a queue, where elements were inserted
at one end and removed from the other.
A solution to this problem is to maintain two references into the collection of links. As
before, the data field firstLink refers to the first link in the sequence. But now a second
data field named lastLink will refer to the final link in the sequence:
To reduce the size of the image the fields in the links have been omitted, replaced with
the graphic arrow. Both the firstLink and lastLink fields can be null if a list is empty.
Removing a data field from the front is the same as before, with the additional
requirement that when the last value is removed and the list becomes empty the variable
lastLink must also be set to null.
Because we have a link to the back, it is easy to add a new value to the end of the list.