Java Reference
In-Depth Information
And we can build a linked list in reverse order with code such as the following:
LinkedList LL = new LinkedList();
System.out.printf("Enter some integers ending with 0\n");
int n = in.nextInt();
while (n != 0) {
LL.addHead(new NodeData(n)); //NodeData argument required
n = in.nextInt();
}
Note that since
addHead
requires a
NodeData
argument, we must create a
NodeData
object with the integer
n
;
this object is passed to
addHead
.
How can we print the items in a list? Presumably, we would like a method (
printList
, say) in the
LinkedList
class, which does the job. But since
LinkedList
does not know what
NodeData
might contain (and it could vary from
one run to the next), how can it print the data in a node?
The trick is to let
NodeData
print itself using the
toString
method. Here is one way to write
printList
:
public void printList() {
Node curr = head;
while (curr != null) {
System.out.printf("%s", curr.data); //invokes curr.data.toString()
curr = curr.next;
}
System.out.printf("\n");
} //end printList
Recall that
curr.data
is a
NodeData
object. Since we use it in a context where a string is required, Java will look
in the
NodeData
class for a
toString
method. Since it finds one, it will use it to print
curr.data
. The
printf
statement
could also have been written as follows where we call
toString
explicitly:
System.out.printf("%s ", curr.data.toString());
If
LL
is a
LinkedList
, the list can be printed with this statement:
LL.printList();
So far, our
LinkedList
class consists of the following:
public class LinkedList {
Node head = null;
public void addHead(NodeData nd) {
Node p = new Node(nd);
p.next = head;
head = p;
}
public void printList() {
Node curr = head;
while (curr != null) {
System.out.printf("%s", curr.data); //invokes curr.data.toString()
curr = curr.next;
}
Search WWH ::
Custom Search