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, use a variable of type
Node1
that always contains a reference to
the first node. In Display 15.3, the variable with a reference to the first node is named
head
. 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, indicate the end of a linked list by setting the
link
instance variable of the
last node in the linked list to
null
, 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 “equal” to
null
by using
==
, and not using any equals method.
Also use
null
to indicate an empty linked list. The
head
instance variable contains
a reference to the first node in the linked list, or it contains
null
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.
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