Java Reference
In-Depth Information
myList
by executing the following instruction:
System.out.println(ListString .lengthRec(myList));
Similarly, we can rewrite with a recursive the previous functions, such as the
belongToRec
function that returns a boolean stating whether a given element
is inside a list or not:
Program 7.11
Recursive membership function
static boolean
belongToRec(String s , ListString
list )
if
(list==
null
)
return false
;
else
{
if
(s.equals(list .name))
return true
;
else
return
belongToRec(s , l i s t . next ) ;
}
}
The recursive display procedure is written as:
Program 7.12
Recursive display of a list
static void
DisplayRec(ListString
list )
{
if
(list==
null
)
System . out . println (
"null"
);
else
{
System . out . print ( l i s t .name+
"-->"
);
DisplayRec( l i s t . next) ;
}
}
Note that if we choose to call function
DisplayRec
before
printing on the console
the current cell by interchanging the two lines in the else-case as follows:
Program 7.13
Reversed recursive display of a list
static void
DisplayRecRev(ListString
list )
{
if
(list==
null
)
System . out . print (
"null"
);
else
{
DisplayRecRev ( l i s t . next ) ;
System . out . print (
"<--"
+list .name) ;
}
}
Then because of the mechanism of the function call stack, the list will be
displayed from the tail to its head. Indeed, the first word written to the output
Search WWH ::
Custom Search