CMPU 102 - Lab 5

In this lab you will modify a linked list class so that it maintains its elements in sorted order.

The following diagram shows a singly-linked list, which consists of a sequence of nodes, each storing one element of a list.

You will modify a class called SortedLinkedList so that, like its name implies, it adds new elements to the list in sorted order.  The version of the class you will be given adds all elements to the end of the list.  You will modify the class so that it inserts elements at the beginning, middle, or end of the list as required to ensure that all of the list elements are sorted.  For example, in the list shown above, the elements (Strings) could have been added in any order.  For example, if the nodes were added in the order "Q", "C", "G", the resulting list would have the elements in the order "C", "G", "Q".

Start out by figuring out, on paper, how you would insert a new node at the beginning, middle, or end of the list.  For example, by inserting the elements "A", "J", and "Z".  Hint: to insert a node in the middle of the list, you will need references to the nodes before and after the place where you are inserting the new node.  The tricky part of your code will be making sure you always have references to the nodes before and after the location where you are considering inserting the new node.

To compare the element you are inserting with an existing element, use the Comparator stored in the comparator field.  Here is how you should use the comparator:

E elementToInsert = ...
E existingElement = ...

int cmp =, existingElement);
if (cmp < 0) {
    elementToInsert is less than existingElement
} else if (cmp > 0) {
    elementToInsert is greater than existingElement
} else {
    elements are equal

Getting started

Start a web browser using the small Firefox button on the task bar at the bottom of the screen, or by typing

firefox &
in a terminal window and hitting return.  Go to the class web page, scroll down to the "Labs" section, and download the file into your home directory.

Start Eclipse by typing

eclipse &
in a terminal window and hitting return.  Once it starts up, choose "File->Import->Existing Projects into Workspace" from the menu, click the "Next" button, click "Select archive file", select the file "" in your home directory, and click the "Finish" button.  You will see a new project called "lab5" in the Package Explorer.  You task is to modify the SortedLinkedList class.

Testing your work

Right click on the file "" in the Package Explorer and choose "Run As->JUnit Test".  You are done when you demonstrate to me that all of the tests pass.  You don't need to add any new tests.


Submit your completed project by entering the following commands in a terminal window (pressing return after each command):

cd eclipse-workspace
submit102 lab5