Java Reference
In-Depth Information
To detect whether or not a given string has already been inserted inside a linked
list, we traverse again the list but now performs the equality test of strings as
follows:
static boolean belongTo( String s ,
ListString
l i s t )
{ while (list!= null )
{ // Use equals method of String that take a String as its
argument
if (s.equals(list .name))
return true ;
list=list .next;
return false ;
}
7.2.6 Length of a linked list
The length of a linked list is defined as its number of elements. To determine
the length of a given linked list, we browse the list starting from its head
until we reach the tail, incrementing by one every time we traverse a cell. The
static (class) function length takes as argument a reference to a list of strings:
a variable of type ListString .
Program 7.5 Static (class) function computing the length of a list
static int length(ListString
list )
{ int l=0;
while (list!= null )
{ l ++;
list=list .next;
}
return l;
}
Once again, observe that since Java is passing function arguments only
by value (using references for objects such as lists), at the end of the
function the original value (reference) of list is preserved although we perform
list =list .next; instructions inside the body of the function. Thus we can call
twice the static length function of class ListString ; it will return the same length
(as expected).
System.out. println(ListString . length(u)) ; // reference to list
u is kept preserved
System.out. println(ListString . length(u)) ;
 
Search WWH ::




Custom Search