diff options
| author | Alexander Pickering <alexandermpickering@gmail.com> | 2017-02-06 11:41:36 -0500 |
|---|---|---|
| committer | Alexander Pickering <alexandermpickering@gmail.com> | 2017-02-06 11:41:36 -0500 |
| commit | 89cdf3efb49335e7c07a68a5a64657eeec2288a6 (patch) | |
| tree | cdc0fd8165e65b1637fa54cac11c932acefc8a89 /labs/lab09_iterator/SListIterator.java | |
| download | coe0445-master.tar.gz coe0445-master.tar.bz2 coe0445-master.zip | |
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; + } + } +} |
