My problem:
The solution of my problem is:
Consider the smaller problem insert(head.next, e):
The solution of insert(head.next, e) is:
Suppose we have the solution of insert(head.next, e) avialable:
How can we use this solution to solve our original problem ?
Answer:
What remains: find a simple case to use a base case
Base case: (insert in an empty list)
Solution:
public static List insert( List head, List e )
{
List helpSol;
/* --------------------------------------------
Base case: insert at the tail of an empty
-------------------------------------------- */
if ( head == null )
{
|
DEMO: /home/cs255001/demo/recursion/InsertList.java
public static List insert( List head, List e )
{
/* --------------------------------------------
Base case: insert at the tail of an empty
-------------------------------------------- */
if ( head == null )
{
e.next = null; // Mark e as the last list elem
return(e); // e is the first list elem !
}
else
{
/* ===========================================================
Solve the problem USING the solution of a smaller problem
=========================================================== */
head.next = insert( head.next, e ); // Link directly to helpSol
return head; // Return MY solution
}
}
|