Java Reference
In-Depth Information
The corresponding array code would look like this:
int i = 0;
while (i < size) {
System.out.println(elementData[i]);
i++;
}
Assuming that you have some comfort with array-style programming, this exam-
ple might give you some useful insight into linked list programming. There are direct
parallels in terms of typical code, as shown in Table 16.2.
Table 16.2
Array/List Equivalents
Description
Array Code
Linked List Code
Go to front of the list
int i = 0;
ListNode current = list;
Test for more elements
i < size
current != null
Current value
elementData[i]
current.data
Go to next element
i++;
current = current.next;
You may recall that in Chapter 7 we introduced a standard array traversal approach:
for (int i = 0; i < <array>.length; i++) {
<do something with array[i]>;
}
You can write a similar standard linked list traversal pattern:
<temp variable> = <front of list>;
while (<temp variable> != null) {
<do something with <temp variable>.data>;
<temp variable> = <temp variable>.next;
}
Knowing that we like to use for loops for array processing, you can imagine writ-
ing for loops to process linked lists as well. Your previous code could be rewritten as
the following code:
for (ListNode current = list; current != null; current = current.next) {
System.out.println(current.data);
}
Some people like to write their list code this way, but most tend to use while
loops. It's an issue of personal taste.
 
Search WWH ::




Custom Search