Java Reference
In-Depth Information
class Node {
int num;
Node next;
}
The variable top can now be declared as a Node variable, using this:
Node top;
As explained, the declaration of top allocates storage for top but does not allocate storage for any nodes. The
value of top can be the address of a Node object, but, so far, there are no nodes in the list. As we know, we can create a
Node object and assign its address to top with this statement:
top = new Node();
This will create the following:
top
num
0
next
Recall that when an object is created, unless specified otherwise, Java will set a numeric field to 0 and an object
field to null .
We will see how to create linked lists a little later, but first we look at some basic operations that may be
performed on a linked list.
3.2 Basic Operations on a Linked List
For illustrative purposes, we assume that we have a linked list of integers. We ignore, for the moment, how the list
might be built.
3.2.1 Counting the Nodes in a Linked List
Perhaps the simplest operation is to count the number of nodes in a list. To illustrate, we write a function that, given a
pointer to a linked list, returns the number of nodes in the list.
Before we write the function, let's see how we can traverse the items in the list, starting from the first one.
Suppose top points to the head of the list. Consider the following code:
Node curr = top;
while (curr != null) curr = curr.next;
Initially, curr points to the first item, if any, in the list. If it is not null , the following statement is executed:
curr = curr.next;
This sets curr to point to “whatever the current node is pointing to,” in effect, the next node. For example,
consider the following list:
 
Search WWH ::




Custom Search