C语言实现栈的进栈与出栈、输出栈顶元素、元素个数、销毁栈
/********************************引入头文件**************************************************/ #include<stdio.h> #include<stdlib.h> #include<malloc.h> /**********************************定义*******************************************************/ /*定义状态码*/ #define OK 0 //正常 #define ERROR -1 //出错 #define OVERFLOW -2 //内存申请不成功 #define DEFSIZE 10 //栈的默认大小 #define INCREAMSIZE 10 //每次当栈空间满时,增量 /* 定义结构体 */ typedef int Status; //定义状态 typedef int ElemType; //定义栈内元素类型 //定义栈的的数据结构 typedef struct{ ElemType *base; //栈底指针 ElemType *top; //栈顶指针 int stackSize; // 栈大小 int realSize; // 栈当前大小,可以不定义 }SqStack; /*********************************stack操作方法**************************************************/ //初始化一个栈 Status InitStack(SqStack &sqstack) { //申请默认栈大小 sqstack.base = (ElemType*)malloc(DEFSIZE*sizeof(ElemType)); if(!sqstack.base) exit(OVERFLOW); sqstack.top = sqstack.base; sqstack.stackSize = DEFSIZE; sqstack.realSize = 0; return OK; } //进栈 Status Push(SqStack &sqstack,ElemType &e) { if(sqstack.top-sqstack.base>=sqstack.stackSize) { sqstack.base = (ElemType*)realloc(sqstack.base,(sqstack.stackSize+INCREAMSIZE)*sizeof(ElemType)); //如果申请失败返回溢出 if(!sqstack.base) exit(OVERFLOW); sqstack.top = sqstack.base + sqstack.stackSize; sqstack.stackSize = sqstack.stackSize + INCREAMSIZE; } *sqstack.top++ = e; sqstack.realSize++; return OK; } //出栈 Status Pop(SqStack &sqstack,ElemType &e) { if(sqstack.base==sqstack.top) { exit(ERROR); } e = *--sqstack.top; sqstack.realSize--; return OK; } //得到栈顶元素 Status GetTop(SqStack &sqstack,ElemType &e) { if(sqstack.base==sqstack.top) { exit(ERROR); } e = *(sqstack.top-1); return OK; } //判断栈是否为空 bool IsEmpty(SqStack &sqstack) { if(sqstack.realSize>0) return false; else return true; } //销毁栈 Status DestroyStack(SqStack &sqstack) { sqstack.top = sqstack.base; free(sqstack.base); sqstack.realSize = 0; sqstack.stackSize = DEFSIZE; return OK; } //得到栈的元素个数 int StackLength(SqStack &sqstack) { return sqstack.realSize; } /*******************************主函数************************************************/ int main(int argc, char *argv[]) { SqStack sqstack; int N = 0; //用于记录输入栈的个数 int temp = 0; //用于临时存栈 /****初始化栈***/ InitStack(sqstack); printf("初始化时,堆的大小为:%d\n",sqstack.stackSize); /**根据输入来填充栈**/ printf("请入你想要输入几个数据进栈:"); scanf("%d",&N) ; while(N--) { scanf("%d",&temp); Push(sqstack,temp); printf("进栈的大小为:%d\t",temp); printf("压栈后,栈的大小为:%d,%d\n",temp,sqstack.stackSize); } /**得到栈顶元素**/ GetTop(sqstack,temp); printf("得到栈顶元素为:%d",temp); /**将栈的元素逐一出栈**/ /* printf("现在开始逐一出栈:\n"); while(!IsEmpty(sqstack)){ //如果栈不为空则进行出栈 Pop(sqstack,temp); printf("%d \t",temp); } printf("\n栈输出完成!!\n"); */ DestroyStack(sqstack); printf("销毁栈完成!!\n"); scanf("%d",&temp); return 0; }