LinkedLists
Today we did a few remove methods. Our basic strategy for remove methods is to simply set the next reference of the node before the item we're removing, to the node after the item we're removing. Take a look at monday's lecture for some example pictures. With linked lists we also have to remember our edge cases. Generally this just involves invalid inputs or what happens if the item we're removing is the head or the tail? If it's the head or the tail, then we have to change the references.
public boolean removeNth(int n) { // Makes sure we have at least n-1 elements in our list if ((n<0) || (n>=count)) return false; // If we're removing the head, we have to reset the head reference if (n == 0) { head = head.getNext(); count--; if (count==0) tail = null; return true; } //Walk through the list until the NEXT node contains the item we're looking to remove Node indexNode=head; for (int indexNumber=0; indexNumber< (n-1); indexNumber,indexNode=indexNode.getNext()) ; //If we end up removing the tail, reset the tail if (index.getNext() == tail) tail = index; // set the next reference to be the node after the item we're looking for index.setNext(index.getNext().getnext()); count--; } public boolean removeObject (Object o) { if (count == 0) return false; // head matches if (head.getItem().equals(o)) { head = head.getNext(); count--; if (count==0) tail = null; } // Common case Node index = head; for (; index.getNext() !=null; index=index.getNext()) { if (index.getNext().getItem().equals(o)) { break; } } // Not found if (index.getNext() == null) return false; // Repair tail, if needed if (index.getNext() == tail) tail = index; index.setNext(index.getNext().getNext()); count--; }