Java Reference
In-Depth Information
In general, we like to keep the node class simple, so we don't want to add much to
this. But it is a good idea to include some constructors:
1 // ListNode is a class for storing a single node of a linked
2 // list. This node class is for a list of integer values.
3
4
public class
ListNode {
5
public int
data; // data stored in this node
6
public
ListNode next; // link to next node in the list
7
8 // post: constructs a node with data 0 and null link
9
public
ListNode() {
10
this
(0, null);
11 }
12
13 // post: constructs a node with given data and null link
14
public
ListNode(
int
data) {
15
this
(data, null);
16 }
17
18 // post: constructs a node with given data and given link
19
public
ListNode(
int
data, ListNode next) {
20
this
.data = data;
21
this
.next = next;
22 }
23 }
Like the other classes we've seen, this class has one “real” constructor (the one
that takes two arguments). The other two constructors use the
this(...)
notation to
call the third constructor with default values (
0
for the data,
null
for
next
). In the
new version of the class, it is possible to write a single statement to construct the
three-element list we have been studying:
1 // Constructs and prints the list [3, 7, 12]. This version uses
2 // node constructors rather than setting fields of each node.
3
4
public class
Construct2 {
5
public static void
main(String[] args) {
6 ListNode list =
new
ListNode(3,
7
new
ListNode(7,
new
ListNode(12)));
8 System.out.println(list.data + " " + list.next.data + " "
9 + list.next.next.data);
10 }
11 }
Search WWH ::
Custom Search