Java Reference
In-Depth Information
The first question to answer is, “What defines a linked list?” That's easy. It's the (object) variable, essentially a
pointer, which points to the first node in the list. So, our class will begin as follows:
public class LinkedList {
Node head = null;
.
.
} //end class LinkedList
We will use head as our “top of list” variable. Java will initialize head to null when we use a statement like the
following, but we do so explicitly to draw attention to its initial value:
LinkedList LL = new LinkedList();
How do we define Node ? Well, it depends on the kind of items (the “data”) that we want to store in the list.
If we want a list of integers, we can use this:
class Node {
int num;
Node next;
}
If we want a list of characters, we can use this:
class Node {
char ch;
Node next;
}
And if we want a list of parts, we can use this:
class Node {
Part part;
Node next;
}
As you can see, we would need to change the definition of Node each time we wanted a different kind of linked
list. But we would also need to change a method if its code depends on the kind of item in the list. Consider, for
example, a method that adds a new node at the head of a list of integers.
public void addHead(int n) {
Node p = new Node(n); //assume Node has the appropriate constructor
p.next = head;
head = p;
}
This can be used, for instance, as follows ( LL is a LinkedList ):
LL.addHead(25);
This will add a node containing 25 at the head of the list, LL .
 
Search WWH ::




Custom Search