Inserting at Tail of a Linked List - with Recursion

  1. Recall that the following recursive definition of a list: click here

  2. A list is an example of a recursive data structure:

  3. The recursive programming technique (recursion) is ideally suited to perform operations on a recursive data structure

  4. We illustrate the use of recursion in implementing list operation by writing a recursive insert method that insert a new element at the tail of the list

  5. The following figure illustrate the steps taken by the recursive method that insert an element at the tail of a list:

  6. The following method "represents" the steps that were shown in the above figure:

    Recursive algorithm to insert new element at tail of list
        // This function returns the head of the list after
        // inserting "newElem" at the tail
        ListElem RecursiveInsert(ListElem head, ListElem newElem)
           ListElem result;
           if ( head == null )
     = null;
              return(newElem);      // Head of a single elem list...
              result = RecursiveInsert(, newElem ); 
    		   // Insert newElem at tail of a shorter list 
    		   // Note: insert() returns the head of the new list !
   = result;	// Link list behind "" 
    	  return(head);		// Return the head of the list

  7. DEMO programs