Circular Linked List
Hello,
I am working with circular linked Lists. Now the thing is that my assignment was to make this. I had to write a set of methods. Now the thing is that I had to write a method that removes the last value. I made it but it doesnt wark and also i am confused
public Object removeFirst()
{
if(size()==0)
return"empty list";
Object temp = last.getNext().getValue();
last.setNext(last.getNext().getNext());
size--;
return temp;
}
//doesnt Work
public Object removeLast()
{
public Object removeLast()
{
if (size()==0)
return"empty list";
Object temp=null;
temp = last.getNext().getValue();
last = last.getNext();
size--;
return temp;
}
}
[1371 byte] By [
JollyJoea] at [2007-10-2 5:48:00]

oops sorry i made a mistake
THE removelast method looks like this
public Object removeLast()
{
if (size()==0)
return "empty list";
Object temp= null;
temp = last.getNext().getValue();
last = last.getNext();
size--;
return temp;
}
Well what is wrong with the code?
Does it compile?
Does it throw an error at runtime?
Does it give you an unexpected answer?
For solving problems like this with next/prev "pointers" I find diagramming boxes with arrows to help understand is an absolute requirement. Try figuring it out on paper.
If you are removing the last item in the list, that means that the item directly before this one, has to the next one in the list
Assuming you have a structure like this:
...--> (n-1) --> (n) --> (1) --> (2) -->...(n-1)
Then removing item (n) you have to make (n-1) point at item (1) as item (n-1) becomes the new "last"
So you have to have the item before the "last" element to keep the next/prev pointers correct.
Yes, I second the drawing-boxes-and-arrows idea. Makes things 1000 times easier. But just to follow on from evnafets, also watch out for special cases like when your list doesn't have any entries, or only has 1 or 2 entries.
Problems:
You will fail when only one element is in the list since last.getNext() == last .
In removeLast you never actually removed the element from the list, you just moved the last pointer to the first element in the list.
In removeLast you are returning the value from the first element, not the last element.