So I am trying to understand LinkedLists better and an exercise is telling me to add the implement the remove() method of the iterator class for my linked list class that I wrote.
My iterator class looks like this:
public java.util.Iterator<T> iterator() {
return new java.util.Iterator<T>() {
Node prev= null,curr = head;
public boolean hasNext() {
if (curr != null) {
return true;
}
return false;
}
public T next() {
T temp = curr.data;
prev = curr;
curr = curr.next;
return temp;
}
public void remove() {
if(prev==null || curr==null)
head=head.next;
else
prev.next=curr.next;
}
};
}
And a test that I wrote for it goes a little something like this:
public void testiterator(){
BasicLinkedList<String> basicList = new BasicLinkedList<String>();
basicList.addToFront("Blue").addToEnd("Red").addToFront("Yellow");
for(Iterator<String> i = basicList.iterator(); i.hasNext();){
if(i.next().equals("Blue"))
i.remove();
}
assertTrue(basicList.toString().equals("\" Yellow Red \""));
}
However when when I print basicList, it tells me that the list contains Yellow and Blue instead of Yellow and Red. Am I implementing the remove() method wrong, am I using it wrong, or both?
Thanks for your time guys!