C++写一个简单的堆栈类


C++写一个简单的堆栈类

  1. /*写一个类栈类,要求完成进栈与出栈*/  
  2. #include<iostream>   
  3. using namespace std;  
  4. const int MAX=5;     //假定栈中最多保存5个数据   
  5. //定义名为stack的类,其具有栈功能   
  6. class stack {  
  7.      //数据成员   
  8.      float num[MAX]; //存放栈数据的数组   
  9.      int top;          //指示栈顶位置的变量   
  10.  public:  
  11.      //成员函数   
  12.      void init(void) { top=0; }    //初始化函数   
  13.      void push(float x)          //入栈函数   
  14.      {  
  15.          if (top==MAX){  
  16.              cout<<"Stack is full !"<<endl;  
  17.              return;  
  18.          };  
  19.          num[top]=x;  
  20.          top++;  
  21.      }  
  22.      float pop(void)          //出栈函数   
  23.      {  
  24.          top--;  
  25.          if (top<0){  
  26.          cout<<"Stack is underflow !"<<endl;  
  27.          return 0;  
  28.          };  
  29.          return num[top];  
  30.      }  
  31.  }  
  32.  //以下是main()函数,其用stack类创建栈对象,并使用了这些对象   
  33.  main(void)  
  34.  {  
  35.      //声明变量和对象   
  36.      int i;  
  37.      float x;  
  38.      stack a,b;    //声明(创建)栈对象   
  39.      //以下对栈对象初始化   
  40.      a.init();  
  41.      b.init();  
  42.      //以下利用循环和push()成员函数将2,4,6,8,10依次入a栈对象   
  43.      for (i=1; i<=MAX; i++)  
  44.          a.push(2*i);  
  45.      //以下利用循环和pop()成员函数依次弹出a栈中的数据并显示   
  46.      for (i=1; i<=MAX; i++)  
  47.         cout<<a.pop()<<" ";  
  48.      cout<<endl;  
  49.      //以下利用循环和push()成员函数将键盘输入的数据依次入b栈   
  50.      cout<<"Please input five numbers."<<endl;  
  51.      for (i=1; i<=MAX; i++) {  
  52.           cin>>x;  
  53.           b.push(x);  
  54.      }   
  55.      //以下利用循环和pop()成员函数依次弹出b栈中的数据并显示   
  56.      for (i=1; i<=MAX; i++)  
  57.         cout<<b.pop()<<" ";  
  58.  }   

相关内容