Rice University - Comp 212 - Intermediate Programming

Fall 2002

Lecture #22 -  Stacks and Queues - The Adapter Pattern


Introduction

Stacks and queues are examples of containers with special insertion and removal behaviors and a special access behavior.

Stack

Insertion and removal in a stack must be carried out in such a way that the last data inserted is the first one to be removed.   One can only retrieve and remove a data element from a stack by way of special access point called the "top".   Traditionally, the insertion and removal methods for a stack are called push and pop, respectively.  push inserts a data element at the top of the stack.  pop removes and returns the data element at the top of the stack.  

A stack is used to model systems that exhibit LIFO (Last In First Out) insert/removal behavior.    There is an extremely versatile (and powerful) calculator called the "reverse-polish-notation" (RPN) calculator.  It uses a "stack" of registers to perform calculations.  One must enter the inputs in the postfix format.  For example, to add 3 to 7, one enters 3 7 +.   The infix expression 3 * (4 + 5) is entered as 3 4 5 + *.  There is no need for parentheses.

Queue

Data insertion and removal in a queue must be carried out in such a way that  the first one to be inserted is the first one to be removed.   One can only retrieve and remove a data element from a queue by way of special access point called the "front".  Traditionally, the insertion and removal methods for a queue are called enqueue and dequeue, respectively.  enqueue inserts a data element at the "end" of the queue.  dequeue removes and returns the data element at the front of the queue.  

A queue is used to model systems that exhibit FIFO  (First In First Out) insertion/removal behavior.  For example, one can model a movie ticket line by a queue.

Implementations

Stacks and queues can be easily implemented by composing with one of the linear recursive structures studied so far.  This is called the "adapter pattern".  The adapter pattern is used to make one class look like another class with a different set of public methods.   It comes in two flavors:

 

 


In Class Exercises

  1. Write an LRStruct visitor to remove the last element.
  2. Write an LRStruct visitor to insert at the end of the LRStruct.
  3. Put together 1/ and 2/ to implement a Queue.
D. X. Nguyen, October 18, 2002
dxnguyen@rice.edu