Return to the lecture notes index

Lecture #12 (February 10, 2006)

Last week, we wrote a method removeNth, that walked through the linked list and removed the nth element. Today, we wrote a method removeObject, that will remove a specific item from the list.

This method will be very similar but instead of knowing the position we are passed the item as a parameter.

public void removeObject(Object item){ // special case if the LinkedList is empty if(count==0) return; //special case is we want to remove the first item in the list if(head.getItem().equals(item)) { removeFirst(); return; } // special case if we want to remove the last item in the list if(tail.getItem().equals(item)){ removeLast(); return; } // we know it is either in the middle or not in the list at all Node index = head; while(index !=tail &&(!index.getNext().getItem().equals(item))){ index=index.getNext(); } // the loop either got us to the right place or it is not in the list // if it is not in the list we return and are done if(index==tail) return; // if it was in the list we are at the right place so we cut it out. index.setNext(index.getNext().getNext()); return; }

It is becoming apparent that Kesden is pushing us towards a particular style of programming. We should clear away the special cases first because that factors it out of the solution. Everything extra in the solution makes it a more complicated solution and not necesarily linearly. The complexity of the code increases quadradically. It is like coordinating a dinner or a meeting. With two or three people coordinating a meeting is fairly easy but by the time you are organizing 8 or 9 people it is impossible to get everyone together. So when you can take something out of a solution, handle it and call it dead it makes the code much simpler. By taking those special cases out of the while loop we had an easy while loop that just had to move forward. So this code is very well structured and it is easy to see the special cases. In writing the code we should comment the cases to make it very apparent what they are. This makes it really easy to follow the logic of the code. Even people with very limited programmming skills can understand this code.