import java.util.Iterator; public class SinglyLinkedList { private ListNode head; public SinglyLinkedList(Type element) { head = new ListNode(element); } public ListNode getFirst() { return head; } public static void main(String[] args) { // Using the most basic implementation. SinglyLinkedList list = new SinglyLinkedList("A"); ListNode node = list.getFirst(); node.setNext(new ListNode("B")); node.getNext().setNext(new ListNode("C")); node.getNext().getNext().setNext(new ListNode("D")); while (node != null) { System.out.println(node); node = node.getNext(); } // Using add methods and iterator. list = new SinglyLinkedList("1"); list.add("2", 1); list.add("3", 2); list.add("4", 3); list.remove(2); Iterator iter = list.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } // Add 3 again, reverse list, and print out. list.add("3", 2); list.reverse(); iter = list.iterator(); System.out.println("Reversed list:"); while (iter.hasNext()) { System.out.println(iter.next()); } } // Extra methods // Insert after current element. public void addToFront(Type element) { ListNode newHead = new ListNode(element); newHead.setNext(head); head = newHead; } public void add(Type element, int index) { if (index == 0) { ListNode newHead = new ListNode(element); newHead.setNext(head); head = newHead; } else { int count = 1; ListNode next = head; while (count < index && next.getNext() != null) { next = next.getNext(); count++; } ListNode newNode = new ListNode(element); newNode.setNext(next.getNext()); next.setNext(newNode); } } public Type remove(int index) { int count = 0; ListNode current = head; ListNode previous = null; while (count < index && current != null) { if (count == index - 1) { previous = current; } current = current.getNext(); count++; } if (current == null) { return null; } else { Type element = current.getElement(); previous.setNext(current.getNext()); return element; } } public void reverse() { ListNode current = head, next = head.getNext(); current.setNext(null); while (next != null) { ListNode temp = next; next = next.getNext(); temp.setNext(current); current = temp; } head = current; } public Iterator iterator() { return new SLLIterator(head); } class SLLIterator implements Iterator { private ListNode current; public SLLIterator(ListNode head) { current = head; } public boolean hasNext() { return current != null; } public IteratorType next() { if (current == null) { return null; } else { IteratorType next = current.getElement(); current = current.getNext(); return next; } } public void remove() { } } } class ListNode { private NodeType element; private ListNode next; public ListNode(NodeType element) { this.element = element; } public void setNext(ListNode next) { this.next = next; } public ListNode getNext() { return next; } public NodeType getElement() { return element; } public String toString() { return element.toString(); } }