中易网

一个简单的链表输出

答案:3  悬赏:50  
解决时间 2021-03-07 09:04
#include "stdio.h"
#include "malloc.h"
#define len sizeof(struct node)
struct node{
int data;
struct node *next;
};

struct node *scanff()
{
struct node *p1;
struct node *head;
int n=0;
struct node *p2;
p1=p2=(struct node *)malloc(len);
scanf("%d",&p1->data);
head=0;
while(p1->data!=0)
{
n++;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct node *)malloc(len);
scanf("%d",&p1->data);
}
p2->next=0;
return(head);
}

void print(struct node *head)
{
struct node *p;
p=head;
if(head!=0)
do{
printf("%d ",p->data);
p=p->next;
}while(p!=0);
}

void main()
{
struct node *head;
head=scanff();
print(head);
}

请各位帮忙看一下这个链表输出程序出现了什么问题,当我输入一些数的时候它没有输出!
最佳答案
怎么会没有输出呢?因为你并没有结束程序
while(p1->data!=0)
{
n++;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct node *)malloc(len);
scanf("%d",&p1->data);
}
注意这个while循环,是当p1->data=0时退出,因此你必须输入0结束输入才会有输出我改了一下程序这样更直观些

#include "stdio.h"
#include "malloc.h"
#define len sizeof(struct node)
struct node{
int data;
struct node *next;
};

struct node *scanff()
{
struct node *p1;
struct node *head;
int n=0;
struct node *p2;
p1=p2=(struct node *)malloc(len);
printf("请连续输入整数 输入0停止\n");
scanf("%d",&p1->data);
head=0;
while(p1->data!=0)
{
n++;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct node *)malloc(len);
scanf("%d",&p1->data);
}
p2->next=0;
return (head);
}

void print(struct node *head)
{
struct node *p;
p=head;
if(head!=0)
do{

printf("%d \n",p->data);
p=p->next;
}while(p!=0);
}

void main()
{
struct node *head;
head=scanff();
printf("你所输入的整数如下:\n");
print(head);
}
全部回答
除程序结束后,没有释放内存之外! 没有问题 至于链表输出的问题,我想应该是你用标准的输入函数scanf, 只要你输入的格式有误就会不打印, 能不能给定些输入的特例
#include "stdlib.h" #include "stdio.h" struct list { int data; struct list *next; }; typedef struct list node; typedef node *link; void main() { link ptr,head,tail; int num,i; tail=(link)malloc(sizeof(node)); tail->next=null; ptr=tail; printf("\nplease input 5 data==>\n"); for(i=0;i<=4;i++) { scanf("%d",&num); ptr->data=num; head=(link)malloc(sizeof(node)); head->next=ptr; ptr=head; } ptr=ptr->next; while(ptr!=null) { printf("the value is ==>%d\n",ptr->data); ptr=ptr->next; }}
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
昨晚煮过的羊奶今天中午能喝吗
现在做房地产销售怎么样?昨天去一家房地产营
爱语烘焙怎么去啊,有知道地址的么
会计人员的办公室一般是几个人一间,是和财务
刚来到深圳 打工 好想家 怎么办
德国菜的上菜顺序 求解答
家户人家这个地址在什么地方,我要处理点事
一首空间装扮的歌曲貌似韩国女生的歌曲画面是
葡萄阴雨天不能剪副梢吗
我按揭了一个车(一万二),做了两家按揭,一
八一年入伍,八六年退伍,服役四年义务兵国家
公积金贷款80万 30年利息是多少
电脑型号 微星 MS-7529 台式电脑 操作系统 Wi
能在网上取消邮政余额查询信息吗?
秀时尚美发会所地址有知道的么?有点事想过去
推荐资讯
霞客大道/X101(路口)在什么地方啊,我要过去
中国邮政储蓄银行(柯街营业所)我想知道这个在
来月经时能骑动感单车吗..
父母写孩子的成长日记怎么写
谁有金宝贝起名软件帮忙起个名字,男孩,2017
凯马聚宝货车,打火着了,挂上档就灭了,在打
如何破212联防,急,为了冠军!注意:我们队
2016年8月21日老龙头几点落潮
钥匙匙什么组词
怎样通过excel来变换矩阵
赣州亿豪商贸有限公司地址在什么地方,想过去
想在呼伦贝尔开一家草原旅游景点,不知道从何
手机登qq时,显示手机磁盘不足,清理后重新登
刺客的套装怎么选啊?