Java Reference
In-Depth Information
7.2.10 Common mistakes when programming lists
Programming linked lists involves handling objects that define structure cells.
Since the tail is defined as the cell having its
next
field set to
null
,thiscan
cause a problem for some code like:
result+=list .name+
"-->"
;
list=list .next;
We need to be sure that variable
list
is never the object since we cannot
access fields of the
null
object. Trying to do so will raise an exception (called
here
nullPointerException
). Thus in general, take particular care when
performing tests like
if
(currentCell!=
null
) ...
to detect whether the current
object
currentCell
is the
null
object or not, before accessing its fields. For
example, we better rewrite the static
head
function as follows:
static int
head( List
l i s t )
{
if
(list!=
null
)
return
list .container;
else
return
−
1;
}
7.3 Recursion on linked lists
By its very nature defined in the abstract framework, the “self-definition” of
lists yields practical recursive algorithms for designing various tasks. Codes for
these algorithms are usually very compact. For example, let us revisit the static
length
function previously described above. We design a recursive function by
considering as a terminal case the
null
list that is of length 0. Otherwise we
return one plus the length of the linked list anchored at the tail for the current
cell. This gives the following compact code:
Program 7.10
Recursive function for computing the length of a list
static int
lengthRec(ListString
list )
{
// terminal case?
if
(list==
null
)
return
0;
else
return
1+l e n g t h R e c ( l i s t . n e x t ) ;
}
Let us attach this static function on class
ListString
by inserting the code inside
the body of the class. Then we display at the output console the length of list
Search WWH ::
Custom Search