go to previous page   go to home page   go to next page highlighting

Answer:

Yes, just as a physical book could be considered as one object, even though it contains many pages each of which could be considered an object.


Linked List as an Object

In the previous chapter main() built a linked list out of Node objects, but the linked list itself was not a self-contained object. It would be nice to have an object that encapsulates the chain of nodes and the methods that manipulate them. This chapter does that.

In practical applications, the nodes of a linked list would usually contain a collection of related data, not just a single integer or a single string. But for now, let us use nodes that contain a single integer.

Our goal is to create a LinkedList object similar to this:

linked list object with three nodes

Here for review is the Node class:

// Node.java
//
public class Node
{
  private int  value;
  private Node next;
  
  public Node ( int val )
  {
    value = val;
    next = null;
  }
  
  public int  getValue() { return value; }
  public Node getNext()  { return next; }
  
  public void setValue( int val ) { value = val; }
  public void setNext( Node nxt ) { next = nxt; } 
  
  public String toString() { return "" + value; }
}

Here is a start on the LinkedList class that contains a pointer to the first node of a chain of nodes:


// LinkedList.java
//
public class LinkedList
{
   // pointer to the first node in the list
   private Node headPtr = null;
  
  // The constructor creates an empty list
  public LinkedList()
  {
    headPtr = null;
  }

  // Determine if the List is empty
  public boolean isEmpty()
  {
     // future work
  }
  
  // Insert one Node containing data at the head
  // of the list.  This will be explained in a few pages.
  public void insertFirst( int data )
  {
    Node newFirst = new Node( data );
    newFirst.setNext( headPtr );
    headPtr = newFirst;
  }
}

The constructor is not really needed since the default constructor would be enough, but is included here to emphasize the initial conditions.

(Recall that if you don't write a constructor for a class, a default constructor is automatically supplied.)


QUESTION 2:

(Thought Question:) Could a LinkedList object not link to any nodes at all?


go to previous page   go to home page   go to next page