Summary: This laboratory helps you gain more experience with the use of lists and pointers.
The previous lab filled in two parts of the program ~walker/152/java-examples/OurSinglyLinkedList.java. For the first part of this lab, you are to fill in the remaining menu option. Specifically, the putFirst (String item) method should take the name of an item on the list and moves that item to the front of the list.
Aside: The following discussion reflects a fairly common circumstance in list processing. Considerable space is taken in what follows to describe what must be done during processing to move a item to the front of a list. The actual coding, however, takes just a very few lines.
To understand how the desired rearrangement of a list might occur, consider the following linked list, represented using the box-and-pointer diagrams of CSC 151:
Of course, if we want to focus on the apple node, then no further processing is needed, since that node is already first.
Processing is more interesting if we want to move the banana node to the front. We consider the steps needed to change the pointers, so that the banana node will be considered the head of the list -- as in the following diagram:
In order to effect this change, we must change three pointer fields:
To begin this work, we first must search the original list to find the item to be moved (e.g., the banana node). Note that in the changed list, the next of the previous node (e.g., the grape node) will have to change. Thus, in searching for the desired node, we also must keep track of the node just before the desired node (which we will call previous). Searching the list to find the desired item then results in the following diagram:
From this picture, we now can change the various next fields, so the banana node will be considered at the head. Work proceeds in three steps, as outlined previously:
Change the next field of the grape node:
Change the next field of the banana node:
Change the head field to the banana node to get the desired new list.
One important type of linked list arises when we want to keep the data in order. For example, numerical data may be in ascending order, or string data may be in alphabetical order. Of course, for such ordered lists, a putFirst method could not be allowed. However, most other methods from our OurSinglyLinkedList can be used directly.
This document is available on the World Wide Web as
http://www.cs.grinnell.edu/~walker/courses/152.sp01/lab-more-lists.html