#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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
- ¥20 怎么用dlib库的算法识别小麦病虫害
- ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
- ¥15 java写代码遇到问题,求帮助
- ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
- ¥15 有了解d3和topogram.js库的吗?有偿请教
- ¥100 任意维数的K均值聚类
- ¥15 stamps做sbas-insar,时序沉降图怎么画
- ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
- ¥15 关于#Java#的问题,如何解决?