Assignment 6
Stack Class

Sample Stack.h

template <class ItemType>
class stack
{
 public:
  void push( ItemType );
  void pop ();
  ItemType top();

  bool empty();

  stack();
  ~stack();

 private:
  struct node
  {
   ItemType item;
   node *next;
  };

  node* head;

};

#include "stack.cpp"
 

Sample Stack.cpp

template <class ItemType>
void stack<ItemType>::push(ItemType I)
{ node* Temp;
  Temp = new node;
  (Temp -> next) = head;
  (Temp -> item) = I;
  head = Temp;
}

template <class ItemType>
void stack<ItemType>::pop ()
{ node* Temp = head;
  head = head -> next;
  delete Temp;
}
 

template <class ItemType>
ItemType stack<ItemType>::top()
{ return (head -> item);
}
 

template <class ItemType>
bool stack<ItemType>::empty()
{ return (head == NULL);
}
 
 

template <class ItemType>
stack<ItemType>::stack()
{  head = NULL;
}
 

template <class ItemType>
stack<ItemType>::~stack()
{  while (! empty())
      pop();
}

Sample Main Program

#include <iostream.h>
#include "stack.h"

void main()
{ stack<char> S;
  stack<int> T;
  char I;
  cout << "Enter 26 letters: ";
  for (int j= 0; j < 26; j++)
   { cin >> I;
     S.push(I);
   }

  cout << endl << endl;

  while(! S.empty())
   { cout << S.top();
     S.pop();
   }
  cout << endl;

  int J=-1;
  while (J != 0)
   {    cout << "Number? ";
       cin >> J;
       T.push(J);
   }

  while (!T.empty())
   {  cout << T.top()<<"   ";
      T.pop();
   }

  cout << endl;