|
|
Example:
|
![]() |
This problem is:
sum( head ) // sum all value in the list starting at head |
|
compute sum( list starting at head ): smallerSol = sum( list starting at head.next ); // Solve a smaller problem solution = head.value + smallerSol; // Use the solution of // a smaller problem to // solve the original prob. |
|
|
|
public static .... SolveProblem( n ) { variables: solution, smallerSol; /* =============================================== Detect and handle base cases FIRST ! =============================================== */ if ( base case detected ) { solution = solve base case; return solution; } else // Then followed by the recursive algorithm { smallerSol = SolveProb( n-1 ); // Recursion !!! solution = find solution using smallerSol; return solution; } } |
Note:
|
public static double sum( Node head ) { double solution, smallerSol; if ( head == null ) { solution = 0; // Solution for the base case return solution; // Return solution } else { smallerSol = sum( head.next ); // Solve smaller problem solution = head.value + smallerSol; // Solve my problem using // solution of smaller problem return solution; // Return solution } } |
|
Output:
myList = [4.0 , 9.0 , 3.0] s = 16.0 |
How to run the program:
|
|
public static void print( Node head ) { if ( head == null ) { return; // Done printing } else { /* ======================================= Change sum() to print() ======================================= */ print( head.next ); // Print a smaller list // ** We changed the method name, so // ** we must use a different method name here ! System.out.print( head.value + " " ); // Print the first value // This is the only "real" change !!! return; // Done } } |
This recursive program prints a list backwards:
myList = [1.0 , 2.0 , 4.0 , 9.0 , 3.0] print(myList): 3.0 9.0 4.0 2.0 1.0 |
How to run the program:
|
public static void print( Node head ) { if ( head == null ) { return; // Done printing } else { /* ======================================= Change sum() to print() ======================================= */ System.out.print( head.value + " " ); // Print the first value FIRST print( head.next ); // Print a smaller list // without the first value NEXT return; // Done } } |
Output:
myList = [1.0 , 2.0 , 4.0 , 9.0 , 3.0] print(myList): 1.0 2.0 4.0 9.0 3.0 |
How to run the program:
|