栈的链式存储

最后更新于:2022-04-01 09:42:54

~~~ #include<stdio.h> #include<windows.h> #include<malloc.h> typedef int elemtype; typedef struct linknode //链表的定义 { elemtype data; struct linknode *next; } listack; void initstack(listack *&s) //初始化 { s=(listack *)malloc(sizeof(listack)); s->next=NULL; } void push(listack *s) //进栈 { int e; listack *p; printf("请输入进栈元素:"); scanf("%d",&e); p=(listack *)malloc(sizeof(listack)); p->data=e; p->next=s->next; s->next=p; printf("进栈成功\n"); } void gettop(listack *s) //取栈顶元素 { int t; if(s->next==NULL) printf("栈空,取值失败!\n"); else { t=s->next->data; printf("取值成功,栈顶元素为:%d\n",t); } } void stackempty(listack *s) //判断链栈是否为空 { if(s->next==NULL) printf("栈为空\n"); else printf("栈不为空\n"); } void pop(listack *&s) //出栈 { listack *p; int e; if(s->next!=NULL) { p=s->next; e=p->data; s->next=p->next; free(p); printf("出栈成功,栈顶元素为:%d\n",e); } else printf("栈为空,出栈失败\n"); } void destroy(listack *&s) { listack *p=s,*q=s->next; char m; getchar(); printf("确定要销毁栈,请输入y 否则不销毁!\n"); scanf("%c",&m); if(m=='y') { while(q!=NULL) { free(p); p=q; q=p->next; } free(p); printf("销毁成功!\n"); exit(0); } else printf("链栈未销毁!\n"); } void main() { listack *s; int m; printf(" ******************欢迎使用**********************\n"); initstack(s); while(1) { printf("请选择:"); printf(" 1 进栈\n"); printf(" 2 判断栈是否为空\n"); printf(" 3 取栈顶元素\n"); printf(" 4 出栈\n"); printf(" 5 销毁栈\n"); printf(" 6 退出\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:exit(0); default:printf("输入错误,请重新输入\n"); } } } ~~~
';