这个生成链表的函数有什麼问题??

来源:百度知道 编辑:UC知道 时间:2024/06/25 08:34:51
p1重复开空间是什麼意思??还是这段代码有错??

struct student *creat()
/*返回一个指向链表头的指针*/
{
struct student *head;
struct student *p1, *p2;
n=0;
p1=(struct student*)malloc(LEN);
p2=(struct student*)malloc(LEN); /*开辟一个新单元*/
scanf("%d %f",&p1->num,&p1->score);
head=NULL;
while (p1->num!=0)
{
n=n+1;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct student*)malloc(LEN);
scanf("%d %f",&p1->num,&p1->score);
}
p2->next=NULL;
return(head);
}

p1=(struct student*)malloc(LEN);
p2=(struct student*)malloc(LEN); /*开辟一个新单元*/
这里改成下面的
p2=p1=(struct student*)malloc(LEN); //使P1P2同指向第一个节点

这样下面的那些构造链表的时候的指针才能对应,才能顺利构造链表- -||
改了就没问题了

帮你改成以下的代码
struct student *creat()
/*返回一个指向链表头的指针*/
{
struct student *head;
struct student *p1, *p2;
p2=p1=(struct student*)malloc(LEN); /*开辟一个新单元*/
head = p2;
scanf("%d %f",&p1->num,&p1->score);
while (p1->num!=0)
{
p1=(struct student*)malloc(LEN);
scanf("%d %f",&p1->num,&p1->score);
p2->next=p1;
p2=p1;
}
p2->next=NULL;
return(head);
}

P1重复开空间是因为链表每个节点都需要空间;
p2=(struct student*)malloc(LEN); /*开辟一个新单元*/ : 这个没必要,p2开的空间没有用,最后会内存泄漏。

学生的作业吧?

这段程序的目的在于生成一个包含头节点的链表,第一次P1的内存块作为偷接点,并不储存数据。并不是说P1重复分配,在else里面是由P2指向当前链表的最后一个节点,而P1只是接收分配内存返回的指针并将该内存块接到链表后面。
这里最大的问题在于判断什么时候链表结束,用分配节点的值来决定链表的结束,这个想法本身