Java Reference
In-Depth Information
Working with Linked Lists
When dealing with a linked list, your code needs to be able to “get to” that first or head
node, and you need some way to detect when the last node is reached. To get your code
to the first node, you use a variable of type
that always contains a reference to the
first node. In Display 15.3, the variable with a reference to the first node is named
Node1
.
From that first or head node your code can follow the links through the linked list. But
how does your code know when it is at the last node in a linked list?
In Java, you indicate the end of a linked list by setting the
head
instance variable of
link
the last node in the linked list to
, as shown in Display 15.4. That way your code
can test whether or not a node is the last node in a linked list by testing whether its
link instance variable contains
null
. Remember that you check for a link being
null
“equal” to
by using
, not any equals method.
null
==
instance variable con-
tains a reference to the first node in the linked list, or it contains
You also use
to indicate an empty linked list. The
null
head
l if the linked list
is empty (that is, if the linked list contains no nodes). The only constructor sets this
head instance variable to null , indicating that a newly created linked list is empty.
nul
empty list
Display 15.4 Traversing a Linked List
head
"rolls"
10
position
"jam"
3
This reference is
position.getLink( ) .
"milk"
1
"tea"
When position is at this last node,
position.getLink( ) == null .
2
null
 
Search WWH ::




Custom Search