public class NodeStack implements Stack {
    private class Node {
        Object data;
        Node next;
    
        Node(Object d, Node n) {
            this.data = d;
            this.next = n;
        }
    }
    
    private Node top;
    
    public NodeStack() {
        this.top = null;
    }

	public int size() {
	    Node ptr = this.top;
	    int count = 0;
	    while (ptr != null) {
	        ptr = ptr.next;
	        count++;
	    }
	    return count;
	}

	public boolean isEmpty() {
        return (top == null);
	}
	
	public Object peek() throws EmptyStackException {
        if (isEmpty())
            throw new EmptyStackException();
        return top.data;
	}
	
	public void push(Object o) {
        this.top = new Node( o, this.top );
	}

	public Object pop() throws EmptyStackException {
        if (isEmpty())
            throw new EmptyStackException();
        Object obj = this.top.data;
        this.top = this.top.next;
        return obj;
	}

	public static void main( String[] args ) {
        NodeStack s = new NodeStack();
        s.push( 4 );
        s.push( 5 );
        try {
            Object obj = s.pop();
            System.out.println( "popped " + obj );
            System.out.println( "peek " + s.peek() );
            s.pop();
            System.out.println( "peek " + s.peek() );
        }
        catch (EmptyStackException e) {
            System.out.println( "but it was empty" );
        }
	}
	
} // end class NodeStack