Example #1
0
// a simple client to drive the stack
// one improvement may be to have the client maintain a free list of unused nodes
int main()
{
   STACK s;
   STACK_NODE *p;
   bool done = false;
   int option, value;
   while( !done )
   {
      cout << "1) push\n2) pop\n3) peek\n4) pop all\n5) init\n"
           << "6) check if empty\n7) quit\n\nEnter option : " << flush;
      cin  >> option;
      switch( option )
      {
      case 1:  cout << "Enter value to push : " << flush;
               cin  >> value;
               p = new STACK_NODE;
               p->key = value;
               s.push( p );
               break;
      case 2:  if( !s.IsEmpty() )
               {
                  p = s.pop();
                  value = p->key;
                  delete p;
                  cout << "Popped " << value << endl;
               }
               else
               {
                  cout << "Nothing to pop!" << endl;
               }
               break;
      case 3:  if( !s.IsEmpty() )
               {
                  // cast off const-ness (but DON't mess with the data!)
                  p = const_cast<STACK_NODE *>(s.peek());
                  value = p->key;
                  cout << "Peeked " << value << endl;
               }
               else
               {
                  cout << "Nothing to peek!" << endl;
               }
               break;
      case 4:  while( !s.IsEmpty() )
               {
                  p = s.pop();
                  value = p->key;
                  delete p;
                  cout << "Popped " << value << endl;
               }
               cout << "Stack is now empty" << endl;
               break;
      case 5:  cout << "Initializing..." << endl;
               s.init();
               break;
      case 6:  cout << "IsEmpty returns " << ( s.IsEmpty() ? "true" : "false" ) << endl;
               break;
      case 7:  done = true;
               break;
      default: cout << "What?" << endl;
      }
   }
   return 0;
}