diff options
Diffstat (limited to 'labs/lab09_iterator/SListIterator.java')
| -rw-r--r-- | labs/lab09_iterator/SListIterator.java | 88 |
1 files changed, 88 insertions, 0 deletions
diff --git a/labs/lab09_iterator/SListIterator.java b/labs/lab09_iterator/SListIterator.java new file mode 100644 index 0000000..e58ea6d --- /dev/null +++ b/labs/lab09_iterator/SListIterator.java @@ -0,0 +1,88 @@ +import java.util.NoSuchElementException; + + +public class SListIterator<T> +{ + private Node firstNode; + private int numberOfEntries; + + public SListIterator() + { + firstNode = null; + numberOfEntries = 0; + } + + public void addToFirst(T aData) + { + firstNode = new Node(aData, firstNode); + numberOfEntries++; + } + + public T getEntry(int givenPosition) + { + T result = null; + + if((givenPosition >= 1) && (givenPosition <= numberOfEntries)) + { + result = (getNodeAt(givenPosition)).data; + } + + return result; + } + + private Node getNodeAt(int givenPosition) + { + Node currentNode = firstNode; + + for(int counter = 1; counter < givenPosition; counter++) + { + currentNode = currentNode.next; + } + + return currentNode; + } + + public Iterator<T> getIterator() + { + return new IteratorForSList(); + } + + private class IteratorForSList implements Iterator<T> + { + Node node; + + private IteratorForSList() + { + node = firstNode; + } + + public boolean hasNext() + { + return node != null; + } + + public T next() + { + T temp = node.data; + node = node.next; + return temp; + } + + public T remove() + { + throw new UnsupportedOperationException("remove() is not supported by this iterator"); + } + } + + private class Node + { + private T data; + private Node next; + + private Node(T aData, Node nextNode) + { + data = aData; + next = nextNode; + } + } +} |
