Inserting at Head of a Linked List

  1. The easiest way to maintain a linked list of element is to insert new elements at the beginning the list...

    (Although insert at the start of a list is easy to do, sometimes it is necessary to insert new elements elsewhere....)

  2. Let's startwith an empty list:

    
        ListElem head = null;     
    
    

  3. Now make a new list element, fill the information portion and link at start:

    
      (1) Make a new list element:
    
         ListElem elem;
         elem = new ListElem(...);
    
    
      (2) Fill the information portion
    
         -- already done by the constrctor. 
         -- You can also assign values like this:
    
         elem.value = 1500;
    
    
      (3) Link new element at start of list:
    
    
         elem.next = head;  // Make new object points 
    		        // to the start of "old list"   
         head = elem;	     // Make "head" points to 
    		        // the **new** starting object
    
    
    Summary: how to link a new element to a list at the start elem = new ListElem(...); // Create list element elem.value = ....; // Optionally fill the // information part elem.next = head; // Make links... head = elem;

     

    Effect of the above program segment on an empty list:

     

    Effect of the above program segment on a non-empty list:

  4. Traversing a linked list:

    Generic code for traversing through all elements in a list:
    
    Given:
    
       ListElem head;  // Points to first element in linked list
    
    How to traverse the linked list:
    
       ListElem ptr;   // Help variable used in list traversal
    
       ptr = head;     // Points to first element in list
       while ( ptr != null )
       {
          "Process the ListElem pointed to by ptr"
    
          ptr = ptr.next;   // ptr points to next element in list 
       }
    
    

    Example: print all values in the list elements
       ListElem ptr;   // Help variable used in list traversal
    
       ptr = head;     // Points to first element in list
       while ( ptr != null )
       {
          System.out.println("Value = " + ptr.value);
    
          ptr = ptr.next;   // ptr points to next element in list 
       }
    
    

  5. DEMO programs