1  import java.util.NoSuchElementException;
  2  
  3  /**
  4     An implementation of a stack as a sequence of nodes.
  5  */
  6  public class LinkedListStack
  7  {
  8     private Node first;
  9     
 10     /** 
 11        Constructs an empty stack.
 12     */
 13     public LinkedListStack()
 14     {  
 15        first = null;
 16     }
 17  
 18     /**
 19        Adds an element to the top of the stack.
 20        @param element the element to add
 21     */
 22     public void push(Object element)
 23     {  
 24        Node newNode = new Node();
 25        newNode.data = element;
 26        newNode.next = first;
 27        first = newNode;
 28     }
 29  
 30     /**
 31        Removes the element from the top of the stack.
 32        @return the removed element
 33     */
 34     public Object pop()
 35     {  
 36        if (first == null) { throw new NoSuchElementException(); }
 37        Object element = first.data;
 38        first = first.next;
 39        return element;
 40     }
 41  
 42     /**
 43        Checks whether this stack is empty.
 44        @return true if the stack is empty
 45     */
 46     public boolean empty()
 47     {
 48        return first == null;
 49     }
 50     
 51     class Node
 52     {  
 53        public Object data;
 54        public Node next;
 55     }
 56  }