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

Answer:

It becomes garbage and is eventually garbage collected.


Insert Last

linked list traversal

To insert a new node at the end of the list: (1) find the last node of the list, (2) link the new node after it.

Check that all cases are handled and that inserting into an empty list works correctly.

  public void insertLast( int data )
  {
    // create a new node
    Node newNode = new Node( data );
    
    // if list is empty
    if ( headPtr == null )
    {
      headPtr = newNode;
    }
    else
    {
      // search for the last node
      Node p = headPtr;
      while ( p.getNext() != null )   
        p = p.getNext();   
        
      // link new node after it
      p.setNext( newNode );
    }
                            
  }

QUESTION 12:

(Thought Question: ) How would you write deleteLast() ?


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