/**
   The DequeStack class implements the Stack interface by means of
   a Deque.

   @author      Franck van Breugel
   @version     1.3    June 7, 2001
   @see Deque
*/
public class DequeStack implements Stack 
{
    private Deque deque; // deque contains the elements of this stack

    /**
       Constructs an empty stack representation by emptying the specified deque.

       @param deque The deque used to implement this stack.
    */
    public DequeStack(Deque deque) 
    {
        while (!deque.isEmpty()) 
        {
            deque.removeLast();
        }
        this.deque = deque;
    }

    public int size() 
    {
        return deque.size();
    }

    public boolean isEmpty()  
    {
        return deque.isEmpty();
    }

    public Object top() throws StackEmptyException 
    {
        try 
        {
            return deque.last(); // last throws DequeEmptyException if deque is empty 
        } 
        catch (DequeEmptyException e) 
        {
            throw new StackEmptyException("Stack is empty.");
        }
    }

    public void push(Object element) 
    {
        deque.insertLast(element);
    }

    public Object pop() throws StackEmptyException 
    {
        try 
        {
            return deque.removeLast(); // removeLast throws DequeEmptyException if deque is empty
        } 
        catch (DequeEmptyException e) 
        {
            throw new StackEmptyException("Stack is empty.");
        }
    }

    /**
       Returns a string representation of this stack.

       @return A string representation of this stack.
    */
    public String toString() 
    {
        return deque.toString();
    }
}
