Java Reference
In-Depth Information
Let's begin by constructing a series of nodes that store the sequence of values [3, 7,
12]. There are three values, which means you'll need three nodes that are linked
together. When you're creating linked lists, if you keep a reference to the front of the
list, then you can get to anything in the list. You'll usually use a single variable of
type
ListNode
that refers to (or points to) the front of the list. You begin with this
declaration:
ListNode list;
The variable
list
is not itself a node. It's a variable that is capable of referring to
a node. You haven't yet given it a value, so you would draw the following picture for
memory at this point in the program:
list
?
The “?” will be replaced with a reference to a node, which means that this box
does not have a
data
field or a
next
field. It's a box where you can store a reference
to such an object. You don't have an actual node yet. To understand this distinction
between an object and a variable that stores a reference to an object, you might want
to review the section on reference semantics in Chapter 7.
The way to get an actual node is to call
new
:
list = new ListNode();
This call constructs a new node and tells Java to have the variable
list
refer to it:
data
0
next
/
list
Recall that when objects are constructed, Java initializes the fields to the zero-
equivalent for the type. That is why in the node above the
data
field has the value
0
and the
next
field has the value
null
. Notice that we use a slash through the box to
indicate a
null
value.
What do you want to do with the node you have constructed? You want to store
3
in its
data
field (
list.data
) and you want its
next
field to point to a new node:
list.data = 3;
list.next = new ListNode();
The addition of these lines of code makes our linked list appear as follows:
data
3
next
data
0
next
/
list
Search WWH ::
Custom Search