Java Reference
In-Depth Information
Table 16.1
Referring to Elements of a Sample List
Expression
Type
Description
Our variable that refers to the first node in the list
list
ListNode
data field of the first node ( 3 )
list.data
int
next field of the first node
list.next
ListNode
data field of the second node ( 7 )
list.next.data
int
next field of the second node
list.next.next
ListNode
data field of the third node ( 12 )
list.next.next.data
int
next field of the third node
list.next.next.next
ListNode
Here is a complete program that includes all this code for constructing a three-
element list along with code that prints the list:
1 // Constructs and prints the list [3, 7, 12] by setting each
2 // field of each node.
3
4 public class Construct1 {
5 public static void main(String[] args) {
6 ListNode list = new ListNode();
7 list.data = 3;
8 list.next = new ListNode();
9 list.next.data = 7;
10 list.next.next = new ListNode();
11 list.next.next.data = 12;
12 list.next.next.next = null;
13 System.out.println(list.data + " " + list.next.data + " "
14 + list.next.next.data);
15 }
16 }
The program produces the following output:
3 7 12
Obviously, this program represents a very tedious way to manipulate a list. It's much
better to write code that involves loops to manipulate lists. But it takes a while to get used
to this idea, so we're first going to practice doing some raw list operations without a loop.
List Basics
Our previous version of the node class has just two fields:
public class ListNode {
public int data;
public ListNode next;
}
 
Search WWH ::




Custom Search