Java Reference
In-Depth Information
public void addInPlace(NodeData nd) {
Node np, curr, prev;
np = new Node(nd);
prev = null;
curr = head;
while (curr != null && nd.compareTo(curr.data) > 0) { //nd is bigger
prev = curr;
curr = curr.next;
}
np.next = curr;
if (prev == null) head = np;
else prev.next = np;
} //end addInPlace
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
} //end class LinkedList
class Node {
NodeData data;
Node next;
public Node(NodeData d) {
data = d;
next = null;
}
} //end class Node
We note that if the Node class were needed by another class, it would be best to declare it public and put it in a
file called Node.java .
3.10 Expanding the LinkedList Class
To prepare for the next example, we will expand the LinkedList class with the following methods. The function
getHeadData returns the data field of the first node, if any, in the list.
public NodeData getHeadData() {
if (head == null) return null;
return head.data;
}
The method deleteHead removes the first node, if any, in the list.
 
Search WWH ::




Custom Search