/* File: SinglyLinkedList.java - March 2018 */ package l10; /** * @author Michael Albert * * Defines an implementation of a basic singly linked list */ public class SinglyLinkedList implements Iterable { private SLLNode first; private SLLNode last; public SinglyLinkedList() { this.first = null; this.last = null; } public void add(T value) { if (this.first == null) { this.first = new SLLNode<>(value, null); this.last = this.first; return; } SLLNode newFirst = new SLLNode<>(value, this.first); this.first = newFirst; } public void addLast(T value) { if (this.first == null) { add(value); return; } SLLNode newLast = new SLLNode<>(value, null); this.last.next = newLast; this.last = newLast; } public T get(int index) { return getNode(index).value; } private SLLNode getNode(int index) throws IndexOutOfBoundsException { if (index < 0) throw new IndexOutOfBoundsException("Negative index"); SLLNode current = this.first; while (current != null && index > 0) { current = current.next; index--; } if (current == null) throw new IndexOutOfBoundsException("Index too large"); return current; } public void add(int index, T value) { if (index == 0) { this.add(value); return; } SLLNode prev = this.getNode(index-1); SLLNode newNode = new SLLNode<>(value, prev.next); prev.next = newNode; } public String toString() { StringBuilder result = new StringBuilder(":"); SLLNode current = this.first; while (current != null) { result.append(current.value); result.append(" --> "); current = current.next; } return result.toString(); } private class SLLNode { private T value; private SLLNode next; private SLLNode(T value, SLLNode next) { this.value = value; this.next = next; } } public java.util.Iterator iterator() { return new java.util.Iterator() { private SLLNode current = first; public boolean hasNext() { return current != null; } public T next() { T result = current.value; current = current.next; return result; } public void remove() { throw new UnsupportedOperationException(); } }; } }