栈《Stack》

来源:互联网 发布:阿里云域名ssl证书 编辑:程序博客网 时间:2024/05/17 23:08

Stack

栈:先进后出

步骤:

1.申请空间:new,建立空栈

2.打印:注意从最后一个元素开始打印

3.入栈,注意是否满栈

4.出栈,注意是否是满栈或者栈空

5.检测栈的状态

 

代码:

 #include<iostream>

  2 using namespace std;

  3

  4 template<class Type>

  5 class Stack

  6 {

  7 public:

  8     Stack()

  9     {

 10         mm = 0;

 11         top = 0;

 12         s = NULL;

 13     }

 14     Stack(int);     //构造函数,建立空栈

 15     void ptr_Stack();   //输出栈顶指针和栈元素

 16     int flag_Stack();   //检测顺序栈的状态

 17     void ins_Stack(Type);   //入栈

 18     Type del_Stack();   //出栈

 19     Type read_Stack();  //读取栈顶元素

 20 private:

 21     int mm;     //存储容量

 22     int top;    //栈顶指针

 23     Type *s;    //栈的首地址

 24 };

 25

 26 //建立容量为mm的空栈

27 template<class Type>

 28 Stack<Type>::Stack(int m)

 29 {

 30     mm = m;

 31     s = new Type[mm];;

 32     top = 0;

 33     return ;

 34 }

 35

 36 //输出

 37 template<class Type>

 38 void Stack<Type>::ptr_Stack()

 39 {

 40     int i;

 41     cout<<"top="<<top<<endl;

 42     for(i=top;i>0;i--)

 43     cout<<s[i-1]<<endl;

 44 }

 45

 46 //检测栈的状态

 47 template<class Type>

 48 int Stack<Type>::flag_Stack()

 49 {

 50     if(top == mm)

 51     return -1;

 52     if(top == 0)

    53     return 0;

 54     return 1;

 55 }

 56

 57 //入栈

 58 template<class Type>

 59 void Stack<Type>::ins_Stack(Type x)

 60 {

 61     if(top == mm)

 62     {

 63         cout<<"Stack is Full!"<<endl;

 64         return ;

 65     }

 66     top = top+1;

 67     s[top-1] = x;

 68     return ;

 69 }

 70

 71 //出栈

 72 template<class Type>

 73 Type Stack<Type>::del_Stack()

 74 {

 75     Type y;

 76     if(top == 0)

  77     {

 78         cout<<"Stack is NULL"<<endl;

 79         return 0;

 80     }

 81     y = s[top-1];

 82     top = top-1;

 83     return y;

 84 }

 85

 86 //读栈顶元素

 87 template<class Type>

 88 Type Stack<Type>::read_Stack()

 89 {

 90     if(top == 0)

 91     {

 92         cout<<"Stack Empty!"<<endl;

 93         return 0;

 94     }

 95     return s[top-1];

 96 }

                     

0 0
原创粉丝点击