X467: Iterators SinglyLinkedList remove()

For this question, assume the following implementation of a singly linked list:

public class SLList<T> implements Iterable<T> {
    private int numberOfEntries;
    private Node<T> head;

    public SLList() {
        head = null;
        this.numberOfEntries = 0;
    }// end default constructor


    public boolean isEmpty() {
        return numberOfEntries == 0;
    }


    public int getNumberOfEntries() {
        return numberOfEntries;
    }


    public void clear() {
        head = null;
        this.numberOfEntries = 0;
    }

    @Override
    public Iterator<T> iterator() {
        return new SLListIterator();
    }


    ...

    //Node
    private class Node<E> {
        private E data; // Entry in bag
        private Node<E> next; // Link to next node

        public Node(E dataPortion) {
            this(dataPortion, null);
        } // end constructor


        public Node(E dataPortion, Node<E> nextNode) {
            data = dataPortion;
            next = nextNode;
        }


        public E getData() {
            if (data != null) {
                return data;
            }
            return null;
        }


        public Node<E> getNext() {
            return next;
        }


        public void setNext(Node<E> newNext) {
            next = newNext;
        }
    } // end Node

    //Iterator
    // Iterator
    public class SLListIterator implements Iterator<T> {
        private Node<T> current;
        private boolean canRemove;

        public SLListIterator() {
            if (head != null) {
                current = head;
            }
            canRemove = false;
        }


        @Override
        public boolean hasNext() {
            return current != null;
        }
        
        @Override
        public boolean next() {
            ...
        }


    }//end iterator


  }

Implement the remove() method in the Iterator class. Check the javadocs if you need help remembering what this method is supposed to do!

You can find documentation for the Iterators at: https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

Remember, that next() must be called before remove can run without error.

For example, consider a singly linked list that looks like this:

  A --> B --> C --> D --> E --> null
  ^
  |
Current

Running next() should change the state to look like this:

  A --> B --> C --> D --> E --> null
        ^
        |
     Current

Running remove() at this point, should remove A from the chain and leave the list looking like this:

 B --> C --> D --> E --> null
 ^
 |
Current

When writing this code, consider how you would remove other letters from this chain like D or E!

Your Answer:

Reset

Practice a different Java exercise

Feedback

Your feedback will appear here when you check your answer.