当前位置:   article > 正文

006.顺序栈C实例_顺序栈实例

顺序栈实例
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define OK 1
  4. #define OVERFLOW -2
  5. #define ERROR -1
  6. #define STACK_INIT_SIZE 100
  7. #define STACKINCREMENT 10
  8. typedef int Status;
  9. typedef struct{
  10. int* base;
  11. int* top;
  12. int stacksize;
  13. }SqStack;
  14. Status printSq(SqStack S)
  15. {
  16. while(S.base!=S.top)
  17. printf("%d ",*(--S.top));
  18. printf("\n");
  19. }
  20. Status InitStack(SqStack* S)
  21. {
  22. S->base=(int*)malloc(STACK_INIT_SIZE*sizeof(int));
  23. if(!S->base)
  24. exit(OVERFLOW);
  25. S->top=S->base;
  26. S->stacksize=STACK_INIT_SIZE;
  27. return OK;
  28. }
  29. Status GetTop(SqStack S,int* e)
  30. {
  31. if(S.top==S.base)
  32. {
  33. return ERROR;
  34. }
  35. e=S.top-1;
  36. return OK;
  37. }
  38. Status Push(SqStack* S,int e)
  39. {
  40. if(S->top-S->base >= S->stacksize)
  41. {
  42. S->base=(int*)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(int));
  43. if(!S->base)
  44. exit(OVERFLOW);
  45. S->top=S->base+S->stacksize;
  46. S->stacksize+=STACKINCREMENT;
  47. }
  48. *S->top++ = e;
  49. return OK;
  50. }
  51. Status Pop(SqStack* S,int* e)
  52. {
  53. if(S->top==S->base)
  54. return ERROR;
  55. *e=*(--S->top);
  56. return OK;
  57. }
  58. int main()
  59. {
  60. int i=0;
  61. int e;
  62. SqStack S;
  63. InitStack(&S);
  64. while(i++<5)
  65. {
  66. printf("input stack elem:\n");
  67. scanf("%d",&e);
  68. Push(&S,e);
  69. }
  70. GetTop(S,&e);
  71. printf("%d\n",e);
  72. while(--i>0)
  73. {
  74. Pop(&S,&e);
  75. printf("%d ",e);
  76. }
  77. return 0;
  78. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/515657
推荐阅读
相关标签
  

闽ICP备14008679号