顺序单栈-C++模板类实现

顺序单栈-C++模板类实现

  1 //模板类:顺序单栈,一种特殊的线性表,单入单出;
  2 #include<iostream>
  3 using namespace std;
  4 #define MAXSIZE 100
  5 
  6 template < typename T >
  7 class Stack{
  8         T data[MAXSIZE];
  9         int cnt;
 10         public:
 11                 Stack(int cnt = -1): cnt(cnt){}
 12                 void InitStack(){
 13                         T a;
 14                         while (cin >> a)
 15                         {
 16                                 data[++cnt] = a;
 17                         }
 18                 }
 19                 bool StackEmpty(){
 20                         if (cnt == -1)
 21                                 return true;
 22                         else
 23                                 return false;
 24                 }
 25                 void push(T e){
 26                         data[++cnt] = e;
 27                 }
 28                 void pop(T& e){
 29                         e = data[cnt--];
 30                 }
 31                 bool StackFull(){
 32                         if (cnt == MAXSIZE - 1)
 33                                 return true;
 34                         else
 35                                 return false;
 36                 }
 37                 void StackTop(T& e){
 38                         e = data[cnt];
 39                 }
 40                 void show(){
 41                         int i = cnt;
 42                         while (i != -1)
 43                                 cout << data[i--] << " " ;
 44                         cout << endl;
 45                 }
 46 };
 47 
 48 
 49 
 50 int main()
 51 {
 52         Stack<int> a;
 53         Stack<char> b;
 54 
 55         a.InitStack();
 56         cout << endl;
 57         a.show();
 58         cout <<"-------------" << endl;
 59         a.push(5);
 60         a.push(6);
 61         a.show();
 62 
 63         cout <<"-------------" << endl;
 64         cout << boolalpha << a.StackFull() << endl;
 65         cout <<"-------------" << endl;
 66         int e;
 67         a.pop(e);
 68         cout << e << endl;
 69         a.show();
 70 
 71         cout <<"-------------" << endl;
 72         cout <<"-------------" << endl;
 73         cout <<"-------------" << endl;
 74         b.push('c');
 75         b.show();
 76         cout <<"-------------" << endl;
 77         char d;
 78         b.pop(d);
 79         cout << d << endl;
 80         b.show();
 81         cout <<"-------------" << endl;
 82         cout << boolalpha << b.StackEmpty() << endl;
 83 
 84         return 0;
 85 }
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页