In the private class LinkedListIterator (which is internal to MyLinkedList), imp
ID: 3806169 • 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
Hi, you can check out the givemn remove() function
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
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() {
// temp stores the current element and prev stores the previous element.
// If temp.next == null, it means that it is the last element and therefore
// we need to remove it. So, because we were storing previous elementin prev, we
// make prev.next = null. Therefore we virtually delete temp.
Node<E> temp = head;
Node<E> prev = null;
while(temp.next!=null){
prev = temp;
temp = temp.next;
}
prev.next = null;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.