Return to the lecture notes index

Lecture #11 (Febrary 10, 2006)

You should have recieved an email with a grade and have feedback for lab 2. If something does not look right with your grade you can always come talk to us. If you come to us either we made a mistake and we will correct it, or you will understand why it was right, and you learn. Either way you are better off so feel free to come talk to us, that is why we are here.

Last time we wrote the basic simple methods for linkedlist today we are going to carve out slightly more complicated methods. Here is the revised java file

LinkedList.java

We are going to write the method removeNth which will remove a node from anywhere in the list.

// the head is the zeroth item of the list, just a reminder
public Object removeNth(long n){
  // lets take care of the special case first the list is empty
  // this is the case if there are no objects in the linkedlist 
  if (count==0){ //this can also be checked without a count variable, just if (head == null)
	return null;
   }
   // special case if we remove the first object in the list
   if (n==0){
   return removeFirst();// this also includes the case if there is only one item
  }

  // special case if we remove the last item in the list
  if(n==(count-1)){
    return removeLast();
   }

Now that we have taken care of all the special cases we can code the meat of this method. Basic logic tells us to step through the list and when we get to the right place we stop. If we want to remove a node we cant stand on the node we want. We have to stop at the node in front of it in order to remove it from the list. Therefore if we want to remove the 5th item we want to go to the 4th item. If we want to remove n we have to stop at (n-1).

This generates the special cases. If there is no objects in the linkedlist then this process will not work. Also if we want to remove the first node in the linkedlist then we have to rename the head. Likewise if we want to remove the last item in the array, we have to move the tail.


 Node posn = head;
 // the comma operator is the sequence operator, it is almost like a semicolon
 //this is really dense code which we do advocate. Dense code is not always 
 //better

 for(long index=0; index<(n-1); index++,posn=posn.getNext())
   ;
 Object tempObj  = posn.getNext().getItem();

 posn.setNext(posn.getNext().getNext());
   count--;

 return tempObj;

}

}