Java Reference
In-Depth Information
When you program linked lists, you have to understand how to access the differ-
ent elements of the structure. The variable list stores a reference to the first node.
You can get inside that node with the dot notation ( list.data and list.next ).
So list.next is the way to refer to the next box of the first node. You wrote code
to assign it to refer to a new node, which is why list.next is pointing at this sec-
ond node.
Now you want to assign the second node's data field ( list.next.data ) to the
value 7 and assign the second node's next field to refer to a third node:
list.next.data = 7;
list.next.next = new ListNode();
Now the linked list looks like this:
data
3
ne xt
data
7
ne xt
data
0
next
/
list
Again, pay close attention to the difference between list , list.next , and
list.next.next, and remember which box is associated with each of these:
data
3
next
data
7
next
data
0
next
/
list
list
list.next list.next.next
Finally, you want to set the data field of this third node to 12 (stored in
list.next.next.data ) and you want to set its next field to null :
list.next.next.data = 12;
list.next.next.next = null;
Our linked list now looks like this:
data
3
next
data
7
next
data
12
next
/
list
The assignment of the next field to null is actually unnecessary because Java ini-
tializes it to that value, but it's not a bad idea to be explicit about the value that you
want to store in the field.
The dot notation is often very confusing for novices, so it is worth pausing for a
moment to make sure that you understand the different combinations and the ele-
ments to which they refer. Table 16.1 includes each of the possibilities for the preced-
ing diagram.
 
 
Search WWH ::




Custom Search