Review of operations on a linked list

  • Operations on a linked list:

    • Insert a new item into the linked list (at any position):

    • Remove an item from the linked list (at any position)

    • Retrieve an item from the linked list (at any position)

  • The principle of each type of algorithm is always the same

    Therefore:

    • Do not memorize

    • Understand what needs to be done

    • Understand the list manipulation operations, such as:

        current = current.next;
      
        current.next = new Node( ... );
      

The insert algorithm

  • Inserting a new node after a node X:

       (1) Find the node X with the list traversal algorithm:
    
           Node<T> current = first;
    
           while ( current != null && current != "node X" )
           {
               current = current.next;
           }
    
       (2) Link the new node after current if node X was found:
    
           if ( current == null )
               handle "not found";
    
           current.next = new Node( ...., current.next );
    
       Notice the general case updates current.next
    

  • Edge case: when insertion requires updating first

    1. Inserting into an empty list
    2. The new node becomes the 1st node in the list

The retrieval algorithm

  • Retrieve the item stored in a node X:

       (1) Find the node X with the list traversal algorithm:
    
           Node<T> current = first;
    
           while ( current != null && current != "node X" )
           {
               current = current.next;
           }
    
       (2) Return the item if node X was found:
    
           if ( current == null )
               handle "not found";
    
           return current.item;
    
       Notice the general case updates current.next
    

  • Edge case: none

The delete algorithm

  • Deleting a node X from a linked list:

       (1) Find the node X while tracking its predecessor 
           with the list traversal algorithm:
    
           Node<T> previous = first;
           Node<T> current  = first;
    
           while ( current != null && current != "node X" )
           {
               previous = current;
               current  = current.next;
           }
    
       (2) Unlink the node X from previous if node X was found:
    
           if ( current == null )
               handle "not found";
    
           previous.next = current.next;
    
       Notice the general case updates previous.next
    

  • Edge case: (1) empty list and (2) when deletion requires updating first

    • (2a) Delete the last remaining node from a list (must set first = null)
    • (2b) Delete the first node from a list (must set first = first.next)