/* ====================================================================== The List object that I use to demo the recursive "insert( )" method ====================================================================== */ class List { int value; List next; public List(int x) { value = x; } } public class InsertList { /* ---------------------------------------------------- main: call insert(head, new List( )) and prints resulting list ---------------------------------------------------- */ public static void main(String[] args) { int[] inp = {1, 9, 3, 8, 5, 6, 7}; List head = null; for ( int i = 0; i < inp.length; i++ ) { System.out.print("List before inserting: " + inp[i] + ": "); print(head); System.out.println(); head = insert(head, new List(inp[i]) ); System.out.print("List after inserting: " + inp[i] + ": "); print(head); System.out.println("\n"); } } /* ================================================= The recursive "insert at tail in list" method ================================================= */ public static List insert( List head, List e ) { List helpSol; /* ----------------------------------------------------- Base case: easy insert at the tail of an empty list ----------------------------------------------------- */ if ( head == null ) { e.next = null; // Mark e as the last list elem return(e); // e is the first list elem ! } else { helpSol = insert( head.next, e ); // Have "someone else" solve // this smaller problem /* =========================================================== Solve the problem USING the solution of a smaller problem =========================================================== */ head.next = helpSol; // Construct MY solution using helpSol return head; // Return MY solution } } /* ====================================== Print the list at h ====================================== */ public static void print(List h) { while ( h != null ) { System.out.print(h.value + " "); h = h.next; } } }