


using the solution of a smaller version of the problem

This is the basis for the recusive algorithm !!!
Node insert( Node head, Node e) { /* =========================================== Recursive algorithm WITHOUT handling of the base case(s) =========================================== */ Node smallerSol; // Suppose head and e are as follows: smallerSol = insert( head.next, e ); // insert( head.next, e ) is this smaller problem: // smallerSol will contains this list: // Solve the original problem: head.next = smallerSol; // Now we have: solution = head; // The solution is the list starting at head // Return the solution list return( solution ); } 


Base cases for list problems are often:


Answer:


if ( head == null ) { e.next = null; solution = e; return solution; } 
static SolveProblem( n ) { variables: solution, smallerSol; if ( base case detected ) { solution = solve base case; return solution; } else { smallerSol = SolveProb( n1 ); // Recursion !!! solution = find solution using smallerSol; return solution; } } 
Note:

private static Node insert( Node head, Node e ) { Node solution, smallerSol; /*  Base case: insert at the tail of an empty  */ if ( head == null ) { e.next = null; // Mark e as the last node solution = e; // return(solution); // return the simple solution ! } else { /* =========================================================== Solve the problem USING the solution of a smaller problem I know the list is not empty... And "head.next" is a SHORTER list ! =========================================================== */ smallerSol = insert( head.next, e ); // Have "someone else" solve // in smaller problem head.next = smallerSol; // Find solution using smallerSol solution = head; return solution; // Return the solution } } 
public static void main( String[] args ) { Node head = null; Node e; e = new Node(4); head = RecursiveList.insert(head, e); // Pass head and e as parameter // Method returns a new list RecursiveList.printList( head ); e = new Node(1); head = RecursiveList.insert(head, e); RecursiveList.printList( head ); e = new Node(3); head = RecursiveList.insert(head, e); RecursiveList.printList( head ); e = new Node(7); head = RecursiveList.insert(head, e); RecursiveList.printList( head ); } 
Output:
[4.0] [4.0 , 1.0] [4.0 , 1.0 , 3.0] [4.0 , 1.0 , 3.0 , 7.0] 
How to run the program:
