Java Reference
In-Depth Information
Example 2•8: LinkedList.java (continued)
if (node != null) {
head = node.getNext();
node.setNext(null);
}
return node;
}
/** Remove and return the node at the end of the list */
public synchronized Linkable removeFromTail() {
if (head == null) return null;
Linkable p = head, q = null, next = head.getNext();
if (next == null) {
head = null;
return p;
}
while((next = p.getNext()) != null) {
q=p;
p = next;
}
q.setNext(null);
return p;
}
/**
* Remove a node matching the specified node from the list.
* Use equals() instead of == to test for a matched node.
**/
public synchronized void remove(Linkable node) {
if (head == null) return;
if (node.equals(head)) {
head = head.getNext();
return;
}
Linkable p = head, q = null;
while((q = p.getNext()) != null) {
if (node.equals(q)) {
p.setNext(q.getNext());
return;
}
p=q;
}
}
/** This nested class defines a main() method that tests LinkedList */
public static class Test {
/**
* This is a test class that implements the Linkable interface
**/
static class LinkableInteger implements Linkable {
int i; // The data contained in the node
Linkable next; // A reference to the next node in the list
public LinkableInteger(int i) { this.i = i; } // Constructor
public Linkable getNext() { return next; } // Part of Linkable
public void setNext(Linkable node) { next = node; } // Linkable
public String toString() { return i + ""; }
// For easy printing
public boolean equals(Object o) {
// For comparison
if (this == o) return true;
if (!(o instanceof LinkableInteger)) return false;
Search WWH ::




Custom Search