/********************************************************** * 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; } // Inserts a new node to the end of this list // take in generic item; Nodes are generic public void addLast(T item) { if(isEmpty()) // Edge case: empty list { first = new Node(item,null); //equivalent: addFirst(item) } else { Node current = first; while(current.next!=null) // Find last lsit element { current = current.next; } current.next = new Node(item,null); // Make list elem + link } } // Delete the node at the end of this list public T removeLast() { if(isEmpty()) // Edge case 1: empty list { // empty list can't remove anything throw new NoSuchElementException(); } if( first.next == null ) // Edge case 2: list has 1 elem { Node ret = first; first = null; return ret.item; } // General case // Find the last node while remembering the previous node Node current = first; Node previous = first; while( current.next != null ) { previous = current; current = current.next; } // Unlink the last node (from its predecessor) previous.next = null; // Return the last node return current.item; } // ============================================================ // Methods below not implemented to focus on the methods above // ============================================================ public void addFirst(T item) { } public T removeFirst() { return null; } public T getFirst() { return null; } public T getLast() { return null; } public T get(int pos) { return null; } public void remove(T key) { } } // End of class