栈的基本操作

来源:互联网 发布:个性淘宝店名 编辑:程序博客网 时间:2024/06/10 17:01

当你看到这个时,你会想起你敲过多少遍:

#include <stdio.h>#include <stdlib.h>#define ElemType int#define Status int#define INIT_SIZE 10//初始化长度#define INCRE_SIZE 10//增量#define OK 1#define ERROR 0#define OVERFLOW -1typedef struct{ElemType *top;//栈顶指针ElemType *base;//栈底指针int stackSize;}SqStack;//初始化栈Status InitStack(SqStack &S){S.base = (ElemType*)malloc(sizeof(ElemType)*INIT_SIZE);if(!S.base){exit(OVERFLOW);}S.top = S.base;//栈顶栈底同时指向底部S.stackSize = INIT_SIZE;return OK;}//取得顶部元素Status GetTop(SqStack S,ElemType &e){if(S.top == S.base){//栈为空,没有元素return ERROR;}e = *--S.top;//栈顶先减后取值return OK;}//进栈Status Push(SqStack &S,ElemType e){if(S.top - S.base >= S.stackSize){//空间已用完S.base = (ElemType*)realloc(S.base,sizeof(ElemType)*INCRE_SIZE);//注意这里是realloc重新分配if(!S.base){exit(OVERFLOW);}S.top = S.base + S.stackSize;//栈顶重新指向栈顶S.stackSize += INCRE_SIZE;}*S.top++ = e;//否则直接赋值到栈顶后栈顶指针往后移return OK;}//出栈Status Pop(SqStack &S,ElemType &e){if(S.top == S.base){return ERROR;}e = *--S.top;//先减后取值return OK;}//判断栈空Status IsStackEmpty(SqStack S){if(S.base == S.top){return OK;}else{return ERROR;}}//判断栈是否满Status IsStackFull(SqStack S){if(S.top - S.base == S.stackSize){return OK;}else{return ERROR;}}//获得栈的长度int GetStackLength(SqStack S){return S.top - S.base;}//销毁栈void DestroyStack(SqStack &S){S.base = S.top = NULL;}//打印栈中元素void PrintStack(SqStack S){ElemType e;SqStack ST;//过渡的栈InitStack(ST);while(S.top != S.base){//将S中的元素逆序Pop(S,e);Push(ST,e);}while(ST.top != ST.base){Pop(ST,e);printf("%d ",e);}DestroyStack(ST);printf("\n");}int main(){//测试SqStack S;InitStack(S);printf("初始化栈成功...\n");ElemType x;printf("输入5个数:");int i = 5;while(i-->0){scanf("%d",&x);Push(S,x);}printf("进栈成功\n");printf("栈中元素为:");PrintStack(S);Pop(S,x);printf("Pop弹出的元素为:%d\n",x);printf("栈中元素为:");PrintStack(S);GetTop(S,x);printf("GetTop的元素为:%d\n",x);printf("栈中元素为:");PrintStack(S);printf("栈的长度为:%d\n",GetStackLength(S));DestroyStack(S);printf("销毁栈成功\n");return 0;}


运行结果:



1 0
原创粉丝点击