/********************************************************** * A Generic Linked List class with a private static inner Node class. *********************************************************/ // We want to "throw" Java exceptions in our code, // so we must import them first: import java.util.NoSuchElementException; // make class name of generic type public class GenericLinkedList implements SimpleList { /******************************************************* The private inner class "Node" *******************************************************/ // make Node class name of generic type private class Node { // Node instance variable is generic private T item; private Node next; // parameters in constructor generic public Node(T item, Node next) { this.item = item; this.next = next; } public String toString(){ return "" + this.item; } } // End of private inner class "Node" /********************************************************/ // SimpleLinkedList instance variable "first" is declared of // type "Node", i.e. the inner class defined above // first is generic node private Node first; // Constructs an empty list public GenericLinkedList() { first = null; } // Returns true if the list is empty public boolean isEmpty() { return first==null; } // Returns a string representation public String toString() { String output = ""; if(first == null) return "[NULL]"; Node tmp = first; while(tmp != null) { output += tmp + " -> "; tmp = tmp.next; } output += "[NULL]"; return output; } // I will use addFirst() to make a linked list to demo the other methods public void addFirst(T item) { Node newNode = new Node(item, first); first = newNode; } // Returns the first element (item) in the list // returns generic type public T getFirst() { if(isEmpty()) { throw new NoSuchElementException(); } return first.item; } // Returns the last element (item) in the list // returns generic type; Nodes are generic public T getLast() { if(isEmpty()) { throw new NoSuchElementException(); } Node current = first; while(current.next!=null) { current = current.next; } return current.item; } // Returns the item at the specified position in the list. // Note: Assume that pos is the index of the node, and that // node indexes start at zero! public T get(int pos) { // Coding strategy: Start by solving the general case, then add checks // for edge cases (e.g. What if "pos" is out-of-bound?) if(isEmpty()) { // empty list throw new NoSuchElementException(); } int i = 0; Node current = first; while( i < pos ) { i++; current = current.next; if(current==null) { // pos past end of list throw new NoSuchElementException(); } } return current.item; } public T removeFirst() { return null; } public void addLast(T item) { } public T removeLast() { return null; } public void remove(T key) { } } // End of class