ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
~~~ #include<stdio.h> #include<windows.h> #include<malloc.h> #define maxsize 50 typedef int elemtype; typedef struct //定义 { elemtype data[maxsize]; int top; }sqstack; void initstack(sqstack *&s) //初始化 { s=(sqstack *)malloc(sizeof(sqstack)); s->top=-1; } void push(sqstack *&s) //进栈 { char e; getchar(); printf("请输入需进栈的元素:"); scanf("%c",&e); if(s->top>maxsize-1) printf("栈满,错误!\n"); else { s->top++; s->data[s->top]=e; printf("进栈成功\n"); } } void gettop(sqstack *s) //取栈顶元素 { char t; if(s->top==-1) printf("栈空,取值失败!\n"); else { t=s->data[s->top]; printf("取值成功,栈顶元素为:%c\n",t); } } void stackempty(sqstack *s) //判断栈是否为空 { if(s->top==-1) printf("栈为空\n"); else printf("栈不为空\n"); } void pop(sqstack *&s) //出栈 { char e; if(s->top==-1) printf("栈为空,出栈失败\n"); else { e=s->data[s->top]; s->top--; printf("出栈成功,出栈元素为:%c\n",e); } } int length(sqstack *s) //求栈长 { if(s->top==-1) return(-1); else return(s->top+1); } void destroy(sqstack *&s) //销毁栈 { char t; getchar(); printf("确定要销毁栈请输入y 否则不销毁:"); scanf("%c",&t); if(t=='y') { free(s); printf("销毁成功\n"); exit(0); } else printf("栈未销毁\n"); } void output(sqstack *s) { int m,n=s->top; m=length(s)+1; if(s->top==-1) printf("栈为空\n"); else { printf("出栈序列为:"); for(;m>0;m--) { printf(" %c",s->data[s->top]); s->top--; } printf("\n"); s->top=n; } } void main() { sqstack *s; printf(" ************欢迎使用顺序栈运算系统*************\n"); int m; initstack(s); while(1) { printf("请选择:"); printf(" 1 进栈\n"); printf(" 2 判断栈是否为空\n"); printf(" 3 取栈顶元素\n"); printf(" 4 出栈\n"); printf(" 5 销毁栈\n"); printf(" 6 求栈的长度\n"); printf(" 7 输出出栈序列\n"); printf(" 8 退出\n"); scanf("%d",&m); switch(m) { case 1:push(s);break; case 2:stackempty(s);break; case 3:gettop(s);break; case 4:pop(s);break; case 5:destroy(s);break; case 6:printf("栈的长度为%d\n",length(s));break; case 7:output(s);break; case 8:exit(0); default:printf("输入错误,请重新输入\n"); } } } ~~~