/** * A doubly linked list. This implementation uses a dummy node. We use * a linked list to store matches in the class Pastiche. * * @author Marcel Turcotte (marcel.turcotte@uottawa.ca) */ import java.util.NoSuchElementException; public class LinkedList implements List { private static class Node { private T value; private Node previous, next; public Node(T value, Node previous, Node next) { this.value = value; this.previous = previous; this.next = next; } } private Node head; private int size; /** * Constructs an empty list. */ public LinkedList() { head = new Node(null, null, null); head.previous = head.next = head; } /** * Returns the number of elements in this list. * * @return the number of elements int this list */ public int size() { return size; } // Helper method, adds an element after the specified node private void addAfter(Node before, E value) { Node after = before.next; before.next = new Node(value, before, after); after.previous = before.next; size++; } // Helper method, removes the element after the specified node private void removeAfter(Node before) { Node after = before.next.next; before.next = after; after.previous = before; size--; } /** * Adds an element at the begining of this list. * * @param value the value to be added * @throws NullPointerException if the value of the parameter is null */ public void addFirst(E value) { if (value == null) { throw new NullPointerException(); } addAfter(head, value); } /** * Adds an element at the end of this list. * * @param value the value to be added * @throws NullPointerException if the value of the parameter is null */ public void addLast(E value) { if (value == null) { throw new NullPointerException(); } addAfter(head.previous, value); } /** * Adds an element at the specified of this list. * * @param value the value to be added * @param pos the specified position * @throws NullPointerException if the value of the parameter is null * @throws IndexOutOfBoundsException if the position is out of range */ public void add(E value, int pos) { if (value == null) { throw new NullPointerException(); } if (pos < 0 || pos > size) { throw new IndexOutOfBoundsException(Integer.toString(pos)); } Node before = head; for (int i=0; i= size) { throw new IndexOutOfBoundsException(Integer.toString(pos)); } Node current = head.next; for (int i=0; i current = head.next; for (int i=0; i current = head.next; while (current != head) { if (buffer.length() > 1) { buffer.append(", "); } buffer.append(current.value.toString()); current = current.next; } buffer.append("]"); return buffer.toString(); } }