X466: Iterators SinglyLinkedList next()

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 remove() {
            ...
        }
        
        


    }//end iterator


  }

Implement the next() 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

Your Answer:

Reset

Practice a different Java exercise

Feedback

Your feedback will appear here when you check your answer.