Java Reference
In-Depth Information
7.2.8 Pretty printer for linked lists
Data-structures based on lists and algorithms processing lists are often more
dicult to debug compared to similar algorithms based on arrays. Therefore,
it is useful to print at the output console the chained cell structure of a given
linked list. Procedure Display does this by traversing the list from its head.
Program 7.7 Pretty printer for lists
static void Display(ListString
list )
{ while (list!= null )
System . out . print ( l i s t .name+ "-->" );
list=list .next;
}
System . out . println ( "null" );
}
We print a list referenced by its head element myList by invoking the instruction
ListString .Display(myList); Instead of printing to the console at every cell
visited, we could also have created a String variable storing the displayed list
and return the string as output:
Program 7.8 Static function writing the structure of a linked list into a String
object
static String Display(ListString
list )
{
String result= "'"'
while(list!=null)
{
result+=list.name+"-->";
list=list.next;
}
result+="null";
return result;
}
We print the list by calling the static function System.out.println(ListString .
Display(myList));
7.2.9 Removing an element from a linked list
To remove an element from a linked list, we first need to search for its position
in the linked list. If the element is found, we need to do a bit of list surgery to
branch the former cell reference next to the next cell element. If the source list
is empty (reference is null ) or if the element is found at the head, we can easily
 
Search WWH ::




Custom Search