LinkedList takes the simple "support clone" attitude towards cloning:
it implements the Cloneable interface, and its clone method does not
throw any exception.  This is possible due to the shallow copy
semantics: the LinkedList.clone method does not need to clone the
objects contained in the list.


class LinkedList implements Cloneable {
    private Object obj;
    private LinkedList next;

    public LinkedList(Object what) {
	obj = what;
    }

    public LinkedList(Object what, LinkedList list) {
	obj = what;
	next = list;
    }

    public Object clone() {
	try {
	    // clone this node, copying object reference
	    LinkedList newList = (LinkedList)super.clone();
	    if (next != null) {
		// recursively clone rest of list
		newList.next = (LinkedList)next.clone();
	    }
	    return newList;
	} catch (CloneNotSupportedException e) {
	    // can't happen
	    throw new InternalError(e.toString());
	}
    }

    public Object getObject() {
	return obj;
    }

    public LinkedList getNextNode() {
	return next;
    }

    public void setNextNode(LinkedList newNext) {
	next = newNext;
    }

    public int numNodes() {
	int count = 1;
	for (LinkedList node = next; node != null; node = node.next)
	    count++;
	return count;
    }

    public String toString() {
	String desc = "(";
	for (LinkedList node = this; node != null; node = node.next) {
	    desc += node.obj;
	    if (node.next != null)
		desc += ", ";
	}
	desc += ")";
	return desc;
    }
}
