CS 3358 (Data Structures and Algorithms) by Lee S. Koh

Implementing Queue Using 2 Stacks
(Queue Class and Algorithms in Pseudocode)

Interface


macro guard
make stack available
make assert() available
class queue:
   public:
      ...  // others (constructors, destructer, etc.) as needed
      void push(item)
      void pop()
      item front()
      bool empty()
   private:
      stack inStack
      stack outStack

Algorithms for Implementation


Assumptions:
(1) capacity of stack is limited only by system resources 
(2) interface for key stack operations as shown below:
       void push(item)
       void pop()
       item top()
       bool empty()

void push(item):
   inStack.push(item)

void pop():
   assert( !inStack.empty() || !outStack.empty() )
   if ( outStack.empty() )
      while ( !inStack.empty() )
         outStack.push( inStack.top() )
         inStack.pop()
   outStack.pop()

item front():
   assert( !inStack.empty() || !outStack.empty() )
   if ( outStack.empty() )
      while ( !inStack.empty() )
         outStack.push( inStack.top() )
         inStack.pop()
   return outStack.top()

bool empty():
   return outStack.empty() && inStack.empty()