import java.util.NoSuchElementException; public class OrderedList implements OrderedStructure { // Implementation of the doubly linked nodes (nested-class) private static class Node { private Comparable value; private Node previous; private Node next; private Node ( Comparable value, Node previous, Node next ) { this.value = value; this.previous = previous; this.next = next; } } // Instance variables private Node head; private Node tail; // Representation of the empty list. public OrderedList() { head = null; tail = null; } // Calculates the size of the list public int size() { Node p = head; int count = 0; while ( p!=null ) { p = p.next; count++; } return count; } // Adding an element while preserving the order public boolean add( Comparable o ) { if ( o == null ) throw new IllegalArgumentException( "null" ); if ( head == null ) { // special case: empty list head = tail = new Node( o, null, null ); } else if ( head.value.compareTo(o) >= 0 ) { // special case: add before first node head = new Node( o, null, head ); head.next.previous = head; } else { Node p = head; // i) there is at least one node // ii) o is greater than p while ( p.next != null && p.next.value.compareTo( o ) < 0 ) { p = p.next; } if ( p.next == null ) { // adding at the end of the list tail.next = new Node( o, tail, null ); tail = tail.next; } else { // intermediate position Node q = p.next; // the node that follows p.next = new Node( o, p, q ); q.previous = p.next; } } return true; } // This implementation does not call size() to determine // if pos is valid; therefore, the list is only traversed // once. public Object get( int pos ) { if (pos < 0) throw new IndexOutOfBoundsException( Integer.toString( pos ) ); Node p = head; for ( int i=0; i