/* Pseudo code for unsorted linked list using dynamic memory Watch out for possible bugs! */ /******************************************************** * insert node, assume node.next = null * return head (because head will change) ********************************************************/ if (head == null) head = node; else { node.next = head; head = node; } return head; /******************************************************** * delete single node, return reference to deleted node ********************************************************/ if (head == null) return null; else { retValue = head; head = head.next; return retValue; } /******************************************************** * find node with value== key. return reference to found node ********************************************************/ for (p = head; p != null && p.value != key; p = p.next) ; return p; /******************************************************** * count number of nodes in list * iterative solution ********************************************************/ for (count = 0, p = head; p != null; count++, p = p.next) ; return count; /* more verbose iterative solution */ count = 0; for (p = head; p!= null; p = p.next) count++; return count; /* recursive solution */ int doCount(list) { if (list == null) return 0; return 1 + doCount(list.next); } /******************************************************** * delete (first) element with value == key ********************************************************/ // empty list if (head == null) return null; // first element is desired element if (head.value == key) { p = head; head = head.next; return p; } // desired element is buried in list // p points to candidate node, q is one node behind p = head.next; q = head; while (p != null && p.value != key) { q = p; p = p.next; } // p now points to desired element, update previous element // in order to remove p from list, then return p q.next = p.next; return p; }