// Quickly banged together Linked-list // 4/17/2001 // Note that items are added 'before' the last one and that the toArray() // function reverses them in the returned array, so they appear in order. // No 'remove' function, just a cheap trick to lose/clear the list. Hope your // garbage collector is working well. // Distribute it however you like. public class MyLinkedList { MyLinkedListNode head; public MyLinkedList() { head = new MyLinkedListNode(); head.setNext(null); } public void add(Object data) { MyLinkedListNode temp = new MyLinkedListNode(data); temp.setNext(head); head = temp; } public void remove(Object objectToRemove) { MyLinkedListNode lastPointer = null; MyLinkedListNode temp = head; while (temp.getNext() != null) { if (temp.getData().equals(objectToRemove)) { // Found the object we want out if (lastPointer == null) head = temp.getNext(); else lastPointer.setNext(temp.getNext()); // end return; } lastPointer = temp; temp = temp.getNext(); } } public int size() { int count = 0; MyLinkedListNode temp = head; while (temp.getNext() != null) { temp = temp.getNext(); count++; } return count; } public Object[] toArray() { Object tempArray[] = new Object[size()]; int index = size()-1; MyLinkedListNode temp = head; while (temp.getNext() != null) { tempArray[index] = temp.getData(); temp = temp.getNext(); index--; } return tempArray; } public String toString() { StringBuffer res = new StringBuffer(); MyLinkedListNode temp = head; while (temp.getNext() != null) { res.append("Item: " + temp.getData().toString() + "\n"); temp = temp.getNext(); } return res.toString(); } public void clear() { head = new MyLinkedListNode(); } public static void main(String args[]) { MyLinkedList m = new MyLinkedList(); m.add(new Integer(343)); m.add("This test String"); m.add(new Double(3.32)); m.add("Another test String"); Object tempArray[] = m.toArray(); System.out.println(m); System.out.println(tempArray[0]); System.out.println(tempArray[1]); System.out.println(tempArray[2]); System.out.println(tempArray[3]); System.out.println(); m.remove(tempArray[0]); System.out.println(m); } }