previous | start | next

Add to Last (cont.)

The complete code:

Node tmp = new Node(20);   // Create a Node for the new value 20
Node p = start;            // Have to begin at the first node

if ( p == null ) {         // start will be null if there are no Nodes yet
  start = tmp;             // If so, make start point to the new Node
} else {

  while( p.next != null ) {// Otherwise, keep moving p to the next Node
    p = p.next;            // until p points to the last Node (where .next is null)
  }
  p.next = tmp;            // Set the next field of the current last Node to the new Node
}
   

This version of add has complexity O(N), where N is the number of data items in the list.



previous | start | next