Linked Lists:
Inside View of the LinkedNodeCollection Class

Alyce Brady
Kalamazoo College

In the first LinkedNodeCollection mini-lab, you implemented a number of basic observer methods in the LinkedNodeCollection and DoublyLinkedNodeCollection classes.  In this lab, you will turn your focus to the add and remove methods.


Mini-Lab 2: Basic Modifier Methods


Understanding the add method for a LinkedNodeCollection

The specification for the LinkedNodeCollection.add method is that it always adds the new element to the beginning of the list. The test cases for the add method include:

The following diagrams illustrate the effect of the add method for these cases.

Adding to Empty List:

Before add
 
After add

 

Adding to A Single-Element List:

Before add
 
After add

 

Adding to A Multiple-Element List:

Before add
 
After add

 

Developing the Code: First Draft

Using these test cases to structure the code, we could develop the following, somewhat verbose, version of the add method.

public boolean add(Object o)
{
    if ( isEmpty() )
    {
        ListNode temp = new ListNode(o, null);
        head = temp;
        numElts = 1;
        return true;
    }
    else if ( size() == 1 )
    {
        ListNode temp = new ListNode(o, head);
        head = temp;
        numElts = 2;
        return true;
    }
    else if ( size() > 1  )
    {
        ListNode temp = new ListNode(o, head);
        head = temp;
        numElts++;
        return true;
    }
    else   //  should never get here!
        return false;
}

Implementing the Modifier Methods for a LinkedNodeCollection


Author: Alyce Brady abrady@kzoo.edu