public class List { int value; List next; // This is a "reference" (= address) variable !! } |
A List object has the following structure:
The offset of the
field value from the
base address is
0
The offset of the
field next from the
base address is
4
Sample list:
|
Example:
|
To understand how you can come up with a recursive algorithm, you must again use the recursive nature of a linked list:
Due to the recusive nature of a linked list, we can use divide and conquer to solve the original problem using the solution of a smaller problem:
(You should recognize that inserting a list element in the original list and inserting a list element in the sub-list is the same kind of problem and can be solved with the same algorithm !!!)
When we write the recursive "insert at the tail" algorithm:
List Insert( List h, List ptr ) { // We are developing this algorith right now... } |
The input parameter h will represent the original list and the input parameter ptr will represent the insert list element
So the Lookup( ) method will be like this:
List Insert( List h, List ptr )
{
if ( list h is empty )
{
return the list with element ptr;
}
else if ( first element is the last element )
{
(1) insert ptr after the first element
(2) return h
}
else if ( 2nd element is the last element )
{
(1) insert ptr after the 2nd element
(2) return h
}
else if ( 3rd element is the last element )
{
(1) insert ptr after the 3rd element
(2) return h
}
and so on....
}
|
Notice that the work done in the highlighted area is the task:
|
So we can replace this code using a Insert( ) call to insert in that sublist:
List Insert( List h, List ptr )
{
if ( list h is empty )
{
return the list with element ptr;
}
else if ( first element is the last element )
{
(1) insert ptr after the first element
(2) return h
}
else
return Insert( h.next, ptr );
}
|
(You just need to use Java expressions to replace the pseudo code in the description)
The Lookup method in Java (without the class, we can add that later) is:
static int Lookup( List h, int searchKey ) { if ( h == null ) return 0; // Not found is represented by 0 else if ( h.key == searchKey ) return (h.value); else return Lookup( h.next, searchKey ); } |
In CS170 or CS171, you would have learn that the cases h == null and h.key == searchKey are called the base cases.
I hope with this approach, you get a feel on how the recursion was introduced:
|
How to run the program:
|