Java Reference
In-Depth Information
console is null since it is the terminal case. Then we pop the function call
stack and write the last cell name string, and so on.
ListString l= new ListString( "Paris" , null );
l= new ListString( "Tokyo" ,l);
l= new ListString( "Berlin" ,l);
l= new ListString( "Porto" ,l);
l= new ListString( "Cambridge" ,l);
l= new ListString( "Roma" ,l);
ListString . Display( l ) ;
ListString .DisplayRec( l ) ;
ListString .DisplayRecRev( l ) ;
System . out . println ( "" );
Roma-->Cambridge-->Porto-->Berlin-->Tokyo-->Paris-->null
Roma-->Cambridge-->Porto-->Berlin-->Tokyo-->Paris-->null
null<--Paris<--Tokyo<--Berlin<--Porto<--Cambridge<--Roma
7.4 Copying linked lists
Copying or cloning objects is an essential operation frequently used in
programs. To copy a list, we need to traverse the source list and create a
new cell every time we visit a list. The snippet code below copy a source list l :
Program 7.14 Copying iteratively a source list but reversing its order
static ListString copy(ListString l )
{ ListString result= null ;
while (l!= null )
{ result= new ListString( l .name, result ) ;
l=l . next ;
return result ;
}
Note that the side-effect of the iterative function copy is to reverse the order
of the linked list. Although it might not be important in some cases, we would
rather get a perfect list clone by using the following recursive procedure:
Program 7.15
Copying a source list by maintaining the original head-tail
order
static ListString copyRec(ListString l )
 
Search WWH ::




Custom Search