Chinaunix首页 | 论坛 | 博客
  • 博客访问: 638057
  • 博文数量: 63
  • 博客积分: 1265
  • 博客等级: 中尉
  • 技术积分: 789
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-06 21:54
文章分类

全部博文(63)

文章存档

2017年(1)

2016年(3)

2015年(2)

2013年(5)

2012年(20)

2011年(32)

分类: LINUX

2011-10-04 21:35:12

  1. #define ERROR 0
  2. #define TRUE 1
  3. #define FALSE 0
  4. #define OK 1
  5. #define EQUAL 1
  6. #define OVERFLOW -1
  7. #define STACK_INIT_SIZE 100 //存储空间初始化分配量
  8. #define STACKINCREMENT 10 //存储空间分配增量

  9. typedef int Status;

  10. typedef struct
  11. {
  12.   SElemType *base;
  13.   SElemType *top; //栈顶指针
  14.   int stacksize;
  15. }SqStack,*pSqStack;

  16. Status InitStack(SqStack **S); //初始化
  17. Status DestroyStack(SqStack *S);
  18. Status ClearStack(SqStack *S);
  19. Status StackEmpty(SqStack S); //判断栈是否为空
  20. int StackLength(SqStack S); //返回栈的长度
  21. Status GetTop(SqStack S,SElemType *e); //用e返回栈顶元素
  22. Status Push(SqStack *S,SElemType e); //向栈订插入元素
  23. Status Pop(SqStack *S,SElemType *e); //出栈
  24. Status StackTraverse(SqStack S,Status (*visit)()); //从栈底到栈顶对栈S中每个元素调用函数visit()

  25. Status InitStack(SqStack **S)
  26. {
  27.   (*S)=(SqStack *)malloc(sizeof(SqStack));
  28.   (*S)->base=(SElemType *)malloc(STACK_INIT_SIZE *sizeof(SElemType));
  29.   if(!(*S)->base)exit(OVERFLOW);
  30.   (*S)->top=(*S)->base;
  31.   (*S)->stacksize=STACK_INIT_SIZE;
  32.   return OK;
  33. }

  34. Status DestroyStack(SqStack *S)
  35. {
  36.  free(S->base);
  37.  free(S);
  38. }

  39. Status ClearStack(SqStack *S)
  40. {
  41.   S->top=S->base;
  42. }

  43. Status StackEmpty(SqStack S)
  44. {
  45.   if(S.top==S.base) return TRUE;
  46.   else
  47.     return FALSE;
  48. }

  49. int StackLength(SqStack S)
  50. {
  51.   int i;
  52.   SElemType *p;
  53.   i=0;
  54.   p=S.top;
  55.   while(p!=S.base)
  56.     {p++;
  57.      i++;
  58.     }
  59. }

  60. Status GetTop(SqStack S,SElemType *e)
  61. {
  62.   if(S.top==S.base) return ERROR;
  63.   *e=*(S.top-1);
  64.   return OK;
  65. }

  66. Status Push(SqStack *S,SElemType e)
  67. {
  68.   if(S->top - S->base>=S->stacksize)
  69.    { S->base=(SElemType *) realloc(S->base,
  70.     (S->stacksize + STACKINCREMENT) * sizeof(SElemType));
  71.      if(!S->base)exit(OVERFLOW);
  72.      S->top=S->base+S->stacksize;
  73.      S->stacksize += STACKINCREMENT;
  74.    }
  75.   *(S->top++)=e;
  76.   return OK;
  77. }

  78. Status Pop(SqStack *S,SElemType *e)
  79. {
  80.   if(S->top==S->base) return ERROR;
  81.   *e=*--S->top;
  82.   return OK;
  83. }

  84. Status StackTraverse(SqStack S,Status (*visit)())
  85. {
  86.   while(S.top!=S.base)
  87.      visit(*(--S.top));
  88. }
阅读(4753) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~