#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct Node{
ElemType data;
struct Node *next;
}Node;
Node *InitStack(Node *top){
top=NULL;
return top;
}
//创建链栈,我感觉是这错了,不知道怎么修改
void Create(Node *top){
Node *p;
int i=1;
ElemType e;
while(i!=0){
scanf("%d",&e);
if(e!=9999){
p=(Node *)malloc(sizeof(Node));
p->data=e;
p->next=top;
top=p;
}else i=0;
}
}
void push(Node *top,ElemType e){
Node *s=(Node *)malloc(sizeof(Node));
s->data=e;
s->next=top;
top=s;
printf("元素%d进栈!\n",s->data);
}
void pop(Node *top){
Node *s=top;
if(s==NULL) printf("该链栈为空,无法出栈!\n");
else{
int e=s->data;
printf("元素%d出栈!\n",e);
top=s->next;
free(s);
}
}
void print(Node *top){
Node *p=top;
if(p==NULL) printf("该链栈为空,无法打印!\n");
else{
printf("该链表的内容为:");
while(p!=NULL){
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
}
int main(){
Node *s;
s=InitStack(s);
printf("链栈初始化成功!\n");
printf("请输入新链栈的值:\n");
Create(s);
print(s);
push(s,15);
print(s);
pop(s);
print(s);
return 0;
}
链栈逻辑错误,无法输出,哪里需要修改?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- 快乐鹦鹉 2022-03-16 21:51关注
Create函数是不对的,不能修改外部的top指针,用返回值,修改如下:
#include <stdio.h> #include <stdlib.h> typedef int ElemType; typedef struct Node{ ElemType data; struct Node *next; }Node; Node *InitStack(Node *top){ top=NULL; return top; } //创建链栈,我感觉是这错了,不知道怎么修改 Node * Create(Node *top){ Node *p; int i=1; ElemType e; while(i!=0){ scanf("%d",&e); if(e!=9999){ p=(Node *)malloc(sizeof(Node)); p->data=e; p->next=top; top=p; }else i=0; } return top; } Node* push(Node *top,ElemType e){ Node *s=(Node *)malloc(sizeof(Node)); s->data=e; s->next=top; top=s; printf("元素%d进栈!\n",s->data); return top; } Node * pop(Node *top){ Node *s=top; if(s==NULL) printf("该链栈为空,无法出栈!\n"); else{ int e=s->data; printf("元素%d出栈!\n",e); top=s->next; free(s); } return top; } void print(Node *top){ Node *p=top; if(p==NULL) printf("该链栈为空,无法打印!\n"); else{ printf("该链表的内容为:"); while(p!=NULL){ printf("%d ",p->data); p=p->next; } printf("\n"); } } int main(){ Node *s = NULL; s=InitStack(s); printf("链栈初始化成功!\n"); printf("请输入新链栈的值:\n"); s = Create(s); print(s); s=push(s,15); print(s); s=pop(s); print(s); return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
- ¥15 linux驱动,linux应用,多线程
- ¥20 我要一个分身加定位两个功能的安卓app
- ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
- ¥15 IAR程序莫名变量多重定义
- ¥15 (标签-UDP|关键词-client)
- ¥15 关于库卡officelite无法与虚拟机通讯的问题
- ¥15 目标检测项目无法读取视频
- ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
- ¥100 求采集电商背景音乐的方法