Skip to main content
ICT
Lesson AB29 - Linked List
 
Main   Previous Next
 

C. Implementing Linked Lists page 5 of 18

  1. In this section, we will look at a class that implements a linked list of ListNode objects. This class encapsulates the list operations that maintain the links as the list is modified. To keep the class simple, we will implement only a singly linked list, and the list class will supply direct access only to the first list element.

  2. The LList class holds a reference, first, to the first ListNode (or null, if the list is completely empty). Access to the first node is provided by the getFirst method. If the list is empty, a NoSuchElementException is thrown (see Lesson A13, Exceptions).

    public class LList<E>
    {
      private ListNode<E> first;

      public LList()
      {
        first = null;
      }

      public E getFirst()
      {
        if (first == null)
        {
          throw new NoSuchElementException();
        }
        else
          return first.getValue();
      }
    }

  3. Additional nodes are added to the head of the list with the addFirst method. When a new link is added to the list, it becomes the head of the list, and the link that the old list had becomes the next link:

    public class LList<E>
    {

      ...
      public void addFirst( E value )
      {
        first = new ListNode<E>( value, first );
      }
      ...
    }

  4. The statement ListNode<E>(value, first) invokes the ListNode constructor. The line of code

    first = new ListNode<E>(value, first);

    is broken down as follows.

    1. The new command allocates enough memory to store a ListNode.

    2. The new ListNode will be assigned the values of value and first

    3. The address of this newly constructed ListNode is assigned to first.

    4. It is important to understand the old and new values of first:

  5. The very first time that addFirst() is called, the instance variable, first, will be null. A new node is constructed with the values value and null and now first points to this new node. The constructor provides a new node between the variable first and the node that first formerly referenced.

    before the call of the constructor

    call the constructor, first is passed as a null value

    first is changed, references the newly constructed node

  6. The second time that addFirst() is called, first is already pointing to the first node of the linked list. When the constructor is called, the new node is constructed and placed between first and the node first used to point to.

    The value of first passed to the ListNode constructor is used to initialize the next field of the new node.

 

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.