Java Reference
In-Depth Information
You can use any variable name you like, although it is common in linked list pro-
gramming to use a name like
current
or
curr
. The preceding line of code initializes
current
to point to the same value as
list
(the first node in the list):
data
3
next
data
5
next
data
2
next
/
list
current
You want a loop that prints the various values, and you want it to keep going as long
as there is more data to print. So how do you structure your loop? The variable
current
will refer to each different node in turn. The final node has the value
null
in its
next
field, so eventually the variable
current
will become equal to
null
and that's when
you know your loop is finished. Thus, your basic loop structure will be as follows:
ListNode current = list;
while (current != null) {
process next value.
move current forward.
}
To process a node, you need to print out its value, which you can get from
current.data
, and you need to move
current
to the next node over. The position
of the next node is stored in
current.next
, so moving to that next node involves
resetting
current
to
current.next
:
ListNode current = list;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
The first time through this loop,
current
is referring to the node with the
3
in it.
It prints this value and then resets
current
, which causes
current
to refer to (or
point to) the second node in the list:
data
3
next
data
5
next
data
2
next
/
list
current
Some people prefer to visualize this differently. Instead of envisioning the variable
current
sitting still while its arrow moves, some people prefer to envision the vari-
able itself moving. So, for the initial situation, you draw the following picture:
Search WWH ::
Custom Search