看看出栈问题在哪里?~
初学栈~出栈出问题了~帮忙看看~程序代码:
#include<stdio.h> #include<stdlib.h> #include<malloc.h> #include<windows.h> #include<conio.h> #include<time.h> #define stack_SIZE 20 #define stack_add_SIZE 10 typedef struct STACK { char* top; //栈顶指针 char* base; //栈底指针 int stacklen; //栈长度 }STACK; void initialization(STACK* s); //初始化 void push(STACK* s,char e); //入栈 void pop(STACK* s,char* e); //出栈 void print(); //获取当前栈元素 int stacklen(STACK* s); //计算当前栈容量 void enpty(STACK *s); //清空栈 void destroy(STACK* s); //销毁栈 int main() { int i=0; int len=0; char ch=0; STACK stack={0}; srand((unsigned )time(NULL)); initialization(&stack); puts("入栈示例:"); len=rand()%50+5; for (i=0;i<len;++i) { ch=rand()%('z'-'a')+'a'; push(&stack,ch); putchar(ch); } printf("\n该栈长度为:%d\n",len); puts("出栈示例:"); while (stack.top!=stack.base) { pop(&stack,&ch); putchar(ch); } puts(""); return 0; } void initialization(STACK* s) { s->top=s->base=(char* )malloc(stack_SIZE*sizeof(char));//分配储存空间 if (s->top==NULL) //检查栈空间分配是否出错 { puts("分配空间失败"); exit(0); } s->stacklen=stack_SIZE; //记录栈空间大小 } void push(STACK* s,char e) { if (s->stacklen==s->top-s->base) //检查是否栈满 { s->base=(char* )realloc(s->base,(s->stacklen+stack_add_SIZE)*sizeof(char));//扩容 s->stacklen+=stack_add_SIZE; //这里要改变栈的长度 } *s->top=e; ++s->top; } void pop(STACK* s,char* e) { if (s->top==s->base) //如果空栈就返回 return ; *e=*--(s->top); } int stacklen(STACK* s) { return (s->top-s->base); } void enpty(STACK* s) { s->top=s->base; //清空 } void destroy(STACK* s) { free(s->base); s->base=NULL; s->top=NULL; s->stacklen=0; }
[此贴子已经被作者于2017-3-6 23:30编辑过]