Deleting at Head of a Linked List

  1. How to remove the FIRST element from a list:

    Code used to delete first element from a list:
        if (head != null ) // Must make sure list is not empty   
        {
           head = head.next;   
        }
    
    

  2. DEMO programs:


  3. How to remove the LAST element from a list:

    The general case:

    There is a special case: list has only one element...

    Code used to delete the last element from a list:
        ListElem last_but_one;
    
        if ( head != null ) // Delete only from non-empty list
        {
           if ( head.next == null )
           {  // Handle special case: List has 1 element
    	  head = null;
           }
           else
           {  // The general case
    
    	  // Find the "last_but_one" element
    	  last_but_one = head;
    	  while ( last_but_one.next.next != null )
    	     last_but_one = last_but_one.next;
    
    	  // Delete element following the "last_but_one" element    
    	  last_but_one.next = null;
           }
    
        }
    
    

  4. DEMO programs: