栈的简单操作

贴一些简单的栈的操作

Code:
  1. #include <stdio.h>   
  2. #include <stdlib.h>   
  3. #include <assert.h>   
  4. #define bool int   
  5. #define true 1   
  6. #define false 0   
  7. #define MAXVAL 100/*the max depth of stack*/   
  8. #define Type float   
  9. struct stack {   
  10.     int sp;/*the next free pos*/  
  11.     Type val[MAXVAL];   
  12. };   
  13.   
  14. struct stack *init_stack()    
  15. {   
  16.     struct stack *s = (struct stack*)malloc(sizeof(struct stack));   
  17.     if (s != NULL)   
  18.         s->sp = 0;   
  19.     return s;   
  20. }   
  21.   
  22. bool push(struct stack *s, Type data)   
  23. {   
  24.     assert(s != NULL);   
  25.     if (s->sp < MAXVAL) {   
  26.         s->val[s->sp++] = data;   
  27.         return true;   
  28.     } else {   
  29.         printf("error: stack full, can't push %g/n", data);   
  30.         return false;   
  31.     }   
  32. }   
  33.   
  34. Type pop(struct stack *s)   
  35. {   
  36.     assert(s != NULL);   
  37.     if (s->sp > 0)   
  38.         return s->val[--s->sp];   
  39.     else {   
  40.         printf("error: stack empty!/n");   
  41.         return 0.0;   
  42.     }   
  43. }   
  44.   
  45. Type top(struct stack *s)   
  46. {   
  47.     assert(s != NULL);   
  48.     if (s->sp > 0)   
  49.         return s->val[s->sp - 1];   
  50.     else {   
  51.         printf("error: stack empty!/n");   
  52.         return 0.0;        
  53.     }   
  54. }   
  55.   
  56. void clear_stack(struct stack *s)   
  57. {   
  58.     assert(s != NULL);   
  59.     s->sp = 0;   
  60. }   
  61. bool stack_empty(struct stack *s)   
  62. {   
  63.     assert(s != NULL);   
  64.     if (s->sp > 0)   
  65.         return false;   
  66.     else  
  67.         return true;   
  68. }   
  69.   
  70. int main()   
  71. {   
  72.     struct stack *s = NULL;   
  73.     s = init_stack();   
  74.     push(s, 5.2);   
  75.     push(s, 4.8);   
  76.     push(s, 15);   
  77.     printf("%g ", pop(s));   
  78.     printf("%g ", pop(s));   
  79.     printf("%g ", top(s));   
  80.     printf("%g ", pop(s));   
  81.     printf("%g ", pop(s));   
  82.     free(s);   
  83.     return 0;   
  84. }  

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值