CMPSCI 187: Programming With Data Structures

David Mix Barrington

Fall, 2011

Discussion Assignment #6: Implementing Double-Ended Queues

19 October 2011

In our last discussion we introduced and played with double-ended queues, or deques. Here we will implement this data structure, in both a linked and a circular array version. To review, here is the interface we will implement:


    public interface DequeADT<T> {
       public void addToFront (T element);
       public T removeFront ( ) throws EmptyCollectionException;
       public T first ( ) throws EmptyCollectionException;
       public void addToRear (T element);
       public T removeRear ( ) throws EmptyCollectionException;
       public T last ( ) throws EmptyCollectionException;
       public boolean isEmpty ( );
       public int size ( );}

We'll begin with the linked list implementation. In order to be able to implement all the operations in O(1) time each, we will upgrade our LinearNode class to include a pointer from each node to the previous node. You might think that this new class should extend LinearNode, but that turns out to be more trouble than it is worth. This class comes from L&C Chapter 6:


      public class DoubleNode<T> {
         private DoubleNode<T> next;
         private T element;
         private DoubleNode<T> previous;
         public DoubleNode( ) {next = element = previous = null;}
         public DoubleNode(T elem) {this( ); element = elem;}
         public DoubleNode<T> getNext ( ) {return next;}
         public T getElement ( ) {return element;}
         public DoubleNode<T> getPrevious ( ) {return previous;}
         public void setNext (DoubleNode<T> dn) {next = dn;}
         public void setElement (T elem) {element = elem;}
         public void setPrevious (DoubleNode<T> dn) {previous = dn;}}

Exercises:

Question 1: Write a complete class DLDeque<T> the implements the Deque<T> interface using DoubleNode<T> objects. You will want instance fields for the first node, the last node, and the size, and methods for the eight operations.

Our other implementation will again use a circular array. As we discussed last week, this class will not be much different from the class CircularArrayQueue in L&C, or your circular array implementation of DropoutStack in Project #3.

Question 2: Write a complete class CADeque<T> that implements the Deque<T> interface using a circular array of T entries. (Remember that the constructor for a generic object with an array in it is a bit strange.) Don't bother writing code for the doubleCapacity method unless you have time. Also remember that subtracting one from a number modulo n should not be done with something like (x--) % n but that x = (x + n - 1) % n will do.

Last modified 20 October 2011