C语言链表输入输出
发布网友
发布时间:2022-04-26 07:15
我来回答
共3个回答
热心网友
时间:2023-10-08 21:21
struct student *creat(void)
{struct student *head;
struct student *p1,*p2;
n=0;
p1=p2=(struct student*)malloc(LEN);
//这里格式化输入二个数0,0
scanf("%ld,%f",&p1->num,&p1->score);
//head赋值为NULL
head=NULL;
//刚才输入的是0因此不满足条件一次循环都不走
while(p1->num!=0)
{ n=n+1;
if(n==1)head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student*)malloc(LEN);
scanf("%ld,%f",&p1->num,&p1->score);
}
p2->next=NULL;
//所以这时候head还是最初赋的值NULL自然打不出信息
return(head);
}
热心网友
时间:2023-10-08 21:21
程序没错,跳出是因为你输入0,0
热心网友
时间:2023-10-08 21:22
#
include
#
include
#
define
NULL
0
#
define
LEN
sizeof(struct
student)
struct
student
{int
num;
int
score;
struct
student
*next;
};
int
n;
struct
student
*creat(void)
{struct
student
*head;
struct
student
*p1,*p2;
n=0;
p1=p2=(struct
student*)malloc(LEN);
scanf("%d,%d",&p1->num,&p1->score);
head=NULL;
while(p1->num!=0)
{
n=n+1;
if
(n==1)head=p1;
else
{
p1=(struct
student
*)malloc(LEN);
p1->next=NULL;
p2->next=p1;
p2=p1;
scanf("%d,%d",&p1->num,&p1->score);
}
}
return(head);
}
void
print
(struct
student
*head)
{
struct
student
*p;
p=head;
do
{printf
("%d
%d\n",p->num,p->score);
p=p->next;
}while
(p!=NULL);
}
void
main
()
{
print
(creat());
}
代码修改好,主要注意在你没malloc空间就给结构体传值了,所以会出错
scanf("%d,%d",&p1->num,&p1->score);