In the private class LinkedListIterator (which is internal to MyLinkedList), imp
ID: 3806172 • Letter: I
Question
In the private class LinkedListIterator (which is internal to MyLinkedList), implement method remove(). This method removes from the list the last element that was returned by next(). This call can only be made once per call to next(). It can be made only if add(E) has not been called after the last call to next.
private class LinkedListIterator
implements java.util.Iterator<E> {
private Node<E> current = head; // Current index
@Override
public boolean hasNext() {
return (current != null);
}
@Override
public E next() {
E e = current.element;
current = current.next;
return e;
}
@Override
public void remove() {
}
}
Explanation / Answer
@Override
public void remove(){
Node<E> cur = null;
Node<E> prev = null;
//get the node which should be deleted
Node<E> key = next();
if(head == null)
throw new RuntimeException("Node cannot be deleted");
if( head.data.equals(key) )
{
head = head.next;
return;
}
cur = head;
while(cur != null && !cur.data.equals(key) )
{
prev = cur;
cur = cur.next;
}
if(cur == null)
throw new RuntimeException("cannot delete");
//delete cur node
prev.next = cur.next;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.