栈的实现

1 #include"../utili.h"
  2
  3 typedef struct Stack
  4 {
  5     ElemType *base;
  6     size_t capacity;
  7     int top;
  8 }Stack;
  9
 10 void init_stack(Stack *st);//初始化栈
 11 void push(Stack *st,ElemType x);//入栈
 12 bool isfull(Stack *st);//判满
 13 bool isempty(Stack *st);判空
 14 void show_stack(Stack *st);
 15 void pop(Stack *st);//出栈
 16 ElemType gettop(Stack *st);//取栈顶元素
 17 ///
 18
 19 void init_stack(Stack *st)
 20 {
 21     st->base =(ElemType*)malloc(sizeof(ElemType)*(DEFAULT_SIZE));
 22     assert(st->base != NULL);
 23     st->capacity = DEFAULT_SIZE;
 24     st->top = 0;
 25 }
 26 void show_stack(Stack *st)
 27 {
 28     for(int i =st->top-1;i>=0;--i)
 29     {
 30         cout<<st->base[i]<<endl;
 31     }
 32 }
 33 bool isfull(Stack *st)
 34 {
 35     if(st->top >= st->capacity)
 36         return TRUE;
 37     return FALSE;
38 }
 39
 40 bool isempty(Stack *st)
 41 {
 42     if(st->top == 0)
 43         return TRUE;
 44     return FALSE;
 45 }
 46 void push(Stack *st,ElemType x)
 47 {
 48     if(isfull(st))
 49     {
 50         cout<<"stack full"<<endl;
 51         return;
 52     }
 53     st->base[st->top++] = x;
 54     //st->top++;
 55 }
 56 void pop(Stack *st)
 57 {
 58     if(isempty(st))
 59     {
 60         cout<<"stack empty"<<endl;
 61         return;
 62     }
 63     st->top--;
 64 }
 65
 66 ElemType gettop(Stack *st)
 67 {
 68     if(!isempty(st))
 69         return st->base[st->top-1];
 70 }

38 }
 39
 40 bool isempty(Stack *st)
 41 {
 42     if(st->top == 0)
 43         return TRUE;
 44     return FALSE;
 45 }
 46 void push(Stack *st,ElemType x)
 47 {
 48     if(isfull(st))
 49     {
 50         cout<<"stack full"<<endl;
 51         return;
 52     }
 53     st->base[st->top++] = x;
 54     //st->top++;
 55 }
 56 void pop(Stack *st)
 57 {
 58     if(isempty(st))
 59     {
 60         cout<<"stack empty"<<endl;
 61         return;
 62     }
 63     st->top--;
 64 }
 65
 66 ElemType gettop(Stack *st)
 67 {
 68     if(!isempty(st))
 69         return st->base[st->top-1];
 70 }

4 int main()
  5 {   
  6     Stack st;
  7     init_stack(&st);
  8     push(&st,1);
  9     push(&st,2);
 10     push(&st,3);
 11     push(&st,4);
 12     push(&st,5);
 13     show_stack(&st);
 14     cout<<"=============="<<endl;
 15     cout<<gettop(&st)<<"pop"<<endl;
 16     pop(&st);
 17     show_stack(&st);
 18     return 0;
 19 }   
~         

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值