Java Reference
In-Depth Information
7.2.7 Dynamic insertion: Adding an element to the list
To add an element to an unordered list, we create a new cell storing that
element and add that cell at the head. The static function
Insert
returns the
reference to the newly created head cell. In other words, we create a new cell
with its container assigned to the value of the element, and with its tail set
to the head of the former list. Note that the element can already have been
inserted.
Program 7.6
Inserting a new element to the list
static
ListString Insert(String s , ListString
list )
{
return new
ListString(s , list ) ;
}
Based on this function, we create a linked list by starting from the
null
cell
and inserting successive elements to the list head.
myList=
null
;
myList=ListString . Insert (
"First"
, myList) ;
//here, we
explicitly means the Insert function of class ListString
myList=
new
ListString(
"Second"
,myList) ;
//Since this code is
located inside the ListString body, we can remove the
class name
...
myList=
null
;
myList
myList=ListString.Insert(”First element”, myList);
”First”
null
myList
”First”
”Second”
null
myList=
new
ListString(”Second element”,myList);
Figure 7.1
Creating a linked list by iteratively calling the static function
Insert
. The arrows anchored at variable
myList
mean references to objects of
type
ListString
Search WWH ::
Custom Search