【C语言 数据结构】栈的极简实现

来源:互联网 发布:学北京话软件 编辑:程序博客网 时间:2024/06/02 20:18
/***结构体SqStack作为栈*SqStack由三部分组成  base是作为栈的底指针  top指向栈顶元素上面的空间 StackSize是栈的大小*@hqweay */ #include<stdio.h>#include<stdlib.h>#include<malloc.h>#define STACK_INIT_SIZE 10#define STACKINCREMENT 2#define OK 1#define NO 2typedef int ElemType;typedef int boolean;struct SqStack{ElemType *base;ElemType *top;int StackSize;};//初始化boolean InitStack(SqStack *list){(*list).base= (ElemType *)malloc(sizeof(ElemType) * STACK_INIT_SIZE);if(!((*list).base)){printf("分配空间失败\n");return NO;}/***一开始令top指向栈底*因为一个元素都没有......... */(*list).top = (*list).base;(*list).StackSize = STACK_INIT_SIZE;printf("初始化成功");return OK;} //入栈boolean Push(SqStack *list, ElemType e){/***入栈首先判断栈是否满了*若满了 需要给栈增加空间 */if((*list).top - (*list).base >= (*list).StackSize){printf("栈满。。。。\n将增加栈的容量\n");(*list).base = (ElemType *)realloc((*list).base, ((*list).StackSize + STACKINCREMENT) * sizeof(ElemType));if(!((*list).base)){printf("分配空间失败\n");return NO;}/**重新分配空间后的栈的top 与 StackSize改变 *虽说如此* 意义是不变的 */(*list).top = (*list).base + (*list).StackSize;(*list).StackSize += STACKINCREMENT;}/***入栈成功 *top 指向下一块空间 */*((*list).top)++ = e;printf("入栈成功\n");return OK;}//出栈boolean Pop(SqStack *list, ElemType *temp){if((*list).base == NULL){printf("没有数据\n");}else{(*temp) =*((*list).top - 1);(*list).top--;}}//清空栈/***清空栈,栈仍存在*只是数据清空*与销毁栈区分.......... */boolean ClearStack(SqStack *list){(*list).top = (*list).base;return OK;}//销毁栈boolean DestroyStack(SqStack *list){free((*list).base);(*list).base = NULL;(*list).top = (*list).base;(*list).StackSize = 0;return OK;}//判断栈是否为空boolean isEmpty(SqStack list){if(list.base != NULL){return OK;}else{return NO;}}//返回栈顶元素 boolean GetTop(SqStack list, ElemType *temp){if(!isEmpty(list)){printf("抱歉  没有元素哦....\n");return NO;}else{*temp = *(list.top - 1);}return OK;} //遍历栈boolean StackTraverse(SqStack list){if(!isEmpty(list)){printf("抱歉  没有元素哦....\n");return NO;}else{ElemType *p = list.base;int i = 1;while(p != list.top + 1){printf("第%d个元素是%d\n", i++, (*p));p++;}}return OK;}int StackLength(SqStack list){ElemType *p = list.base;int length = 1;while(p != list.top + 1){length++;p++;}return length-1;}int main(){SqStack List;ElemType e = 11;ElemType temp;InitStack(&List);  Push(&List, 2);  Push(&List, 1);  Push(&List, 4);  Push(&List, 5);  Push(&List, 7);    Pop(&List, &temp);  printf("%d", temp);   StackTraverse(List);    printf("栈总元素为%d个\n", StackLength(List));return 0;}

0 0
原创粉丝点击