Introduction to Singly-Linked Lists
Summary: This laboratory helps you gain more experience with the
use of lists and pointers.
This lab involves working with lists of data, using an approach
simplified somewhat from Section 6.3 of Bailey's text. In particular,
-
File ~walker/152/java-examples/SinglyLinkedListElement.java
gives Bailey's singly-linked list element class from Section 6.3.
(Unlike Bailey's version, this class is not placed in a separate package.
This simplification will be discussed later in the course.)
-
File ~walker/152/java-examples/OurSinglyLinkedList.java
follows Bailey's linked-list class, with some revisions:
-
To simplify our work, some methods are omitted.
-
For testing, a main testing method is added.
-
For practice in this lab, some method headers are added. (You will get
the chance to fill those methods in shortly.)
Steps for this Lab
-
Review Bailey's discussion of SinglyLinkedListElement
and SinglyLinkedList to be sure you understand that material.
-
Copy SinglyLinkedListElement and OurSinglyLinkedList to
your account and compile them.
-
In OurSinglyLinkedList, review the new main to see how
it may be used for testing. Then run this program with several test
cases in order to gain experience with this main testing method.
-
Note where items are added and removed from the list.
-
Check that the code correctly determines if the list is empty.
-
Explain how the code prints the items on the list. (Think of
StringBuffer s as just a flexible string variable.)
-
Note that methods putFirst, printLast, and count
are present only as stubbs. That is, the method headers are present, but
the code does not actually perform the desired work. This allows the code
to be compiled and tested, but incorrect or incomplete work results when
these methods are called. Record specifically what happens when each of
these methods are called from appropriate menu options. Why do you think
count contains a return statement, while the other two
methods do not?
Such a menu-driven framework often provides a flexible approach for
testing specific methods.
-
Methods contains, remove, and toString all
contain loops that allow processing to work through the list. Follow a
similar approach to implement the details for method printLast,
that should print the data for the last item on the list. (If the
list is null, the method should print a message to that effect
instead.)
To perform this task, you have to move along the list item-by-item
until coming to the end, where the next field is null.
-
Write the details for method count (String item)
which counts the number of times a designated item occurs on
the list.
To perform this task, you will want to move along the list item-by-item,
counting the items as you go.
This document is available on the World Wide Web as
http://www.cs.grinnell.edu/~walker/courses/152.sp01/lab-lists-intro.html
created March 12, 2001
last revised March 13, 2001
Henry Walker (walker@cs.grinnell.edu)