Java Reference
In-Depth Information
We can simplify this diagram by redrawing the three nodes that are now part of the
first list all in a row. Keep in mind, though, that the nodes themselves haven't moved
around in memory. We have only rearranged various links. But we can more easily
understand the structure if we draw the picture in this way:
2
3
5
1
data
2
next
data
4
next
data
3
next
/
p
6
4
data
9
next
/
q
And now we can see that this diagram matches the “after” picture we were given.
The three lines of code that are needed to get from the initial state to the final state
are as follows:
p.next.next = q;
q = q.next;
p.next.next.next = null;
Obviously, this process can be very confusing. It is essential to draw pictures to
keep track of what is pointing where and what is going on when this code executes.
It's the only way to master linked list code.
Traversing a List
Consider the problem of printing each value in a list on a different line. For example,
suppose we have a variable called list that stores a reference to the list [3, 5, 2]:
data
3
next
data
5
next
data
2
next
/
list
Using the techniques from the previous section you could refer to each of the
three data fields: list.data (3) , list.next.data (5) , and list.next.next.data
( 2 ). This approach can work for very short lists, but obviously won't work when you
have hundreds or thousands of nodes to process. In that case, you'd want to write a
loop.
You have just one variable to work with, the variable list , so that's clearly where
you have to start. You could use it to move along the list and print things out, but then
you would lose the original value of the variable, which would mean that you would
have lost the list. Instead, it's better to declare a local variable of type ListNode that
you use to access the different nodes of the list:
ListNode current = list;
 
Search WWH ::




Custom Search