X808: Iterators SinglyLinkedList next()

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

x
 
1
public class SLList<T> implements Iterable<T> {
2
    private int numberOfEntries;
3
    private Node<T> head;
4
5
    public SLList() {
6
        head = null;
7
        this.numberOfEntries = 0;
8
    }// end default constructor
9
10
11
    public boolean isEmpty() {
12
        return numberOfEntries == 0;
13
    }
14
15
16
    public int getNumberOfEntries() {
17
        return numberOfEntries;
18
    }
19
20
21
    public void clear() {
22
        head = null;
23
        this.numberOfEntries = 0;
24
    }
25
26
    @Override
27
    public Iterator<T> iterator() {
28
        return new SLListIterator();
29
    }
30
31
32
    ...
33
34
    //Node
35
    private class Node<E> {
36
        private E data; // Entry in bag
37
        private Node<E> next; // Link to next node
38
39
        public Node(E dataPortion) {
40
            this(dataPortion, null);
41
        } // end constructor
42
43
44
        public Node(E dataPortion, Node<E> nextNode) {
45
            data = dataPortion;
46
            next = nextNode;
47
        }
48
49
50
        public E getData() {
51
            if (data != null) {
52
                return data;
53
            }
54
            return null;
55
        }
56
57
58
        public Node<E> getNext() {
59
            return next;
60
        }
61
62
63
        public void setNext(Node<E> newNext) {
64
            next = newNext;
65
        }
66
    } // end Node
67
68
    //Iterator
69
    // Iterator
70
    public class SLListIterator implements Iterator<T> {
71
        private Node<T> current;
72
        private boolean canRemove;
73
74
        public SLListIterator() {
75
            if (head != null) {
76
                current = head;
77
            }
78
            canRemove = false;
79
        }
80
81
82
        @Override
83
        public boolean hasNext() {
84
            return current != null;
85
        }
86
        
87
        @Override
88
        public boolean remove() {
89
            ...
90
        }
91
        
92
        
93
94
95
    }//end iterator
96
97
98
  }

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:

xxxxxxxxxx
5
 
1
@Override
2
public T next() {
3
    
4
}
5

Feedback

Your feedback will appear here when you check your answer.