顺序栈 代码

来源:互联网 发布:免费seo诊断 编辑:程序博客网 时间:2024/05/16 19:48
#include <stdio.h>#include <malloc.h>typedef int SElemType;#define MAX_SIZE 20//表示形式typedef struct  {SElemType *top;SElemType *base;int stacksize;//当前最大容量}stackLine;//创建bool InitStack(stackLine* stack){(*stack).base = (SElemType*)malloc(sizeof(SElemType)*MAX_SIZE);if (!(*stack).base){return false;}(*stack).top = (*stack).base;(*stack).stacksize = MAX_SIZE;return true;}//销毁void DestroyStack(stackLine* stack){free((*stack).base);(*stack).base = NULL;(*stack).top = NULL;(*stack).stacksize = 0;}//清空void ClearStack(stackLine* stack){(*stack).top = (*stack).base = NULL;}//判空bool StackEmpty(stackLine stack){if (stack.base == stack.top){return true;}return false;}//长度int StackLenght(stackLine stack){int nCount = 0;while(stack.base != stack.top){--stack.top;nCount++;}return nCount;}//取值 SElemType GetTop(stackLine stack){if (stack.base == stack.top){return -1;}return *(stack.top - 1);}//压栈void Push(stackLine* stack, SElemType val){if ((*stack).top - (*stack).base >= (*stack).stacksize){(*stack).base = (SElemType*)realloc((*stack).base,((*stack).stacksize + MAX_SIZE)*sizeof(SElemType));if ((*stack).base == NULL){return;}(*stack).top = (*stack).base + (*stack).stacksize;(*stack).stacksize += MAX_SIZE;}*(*stack).top = val;(*stack).top++;}//弹栈SElemType Pop(stackLine* stack){if ((*stack).base == (*stack).top){return -1;}return *(--(*stack).top);}//遍历void StackTraverse(stackLine stack){while(stack.base != stack.top){printf("%d\n",*(--stack.top));}}int main(){stackLine stack = {0};InitStack(&stack);if (StackEmpty(stack)){printf("空\n");}Push(&stack,1);Push(&stack,2);Push(&stack,3);Push(&stack,4);Push(&stack,5);printf("个数%d\n",StackLenght(stack));printf("头%d\n",GetTop(stack));StackTraverse(stack);printf("pop:%d\n",Pop(&stack));printf("pop:%d\n",Pop(&stack));printf("pop:%d\n",Pop(&stack));printf("个数%d\n",StackLenght(stack));printf("头%d\n",GetTop(stack));printf("pop:%d\n",Pop(&stack));printf("pop:%d\n",Pop(&stack));DestroyStack(&stack);return 0;}