重生之还债:请教一个链表问题

来源:百度文库 编辑:高校问答 时间:2024/05/05 02:37:33
#include "stdafx.h"
#include"stdio.h"
#include"malloc.h"
#define NULL 0
#define LEN sizeof(struct student)
struct student
{long num;
float 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("%ld,%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("%ld,%f",&p1->num,p1->score);}
p2->next=NULL;
return(head);}中的没有p1=p2=(struct student *)malloc(LEN);这句话而是用p1=(struct student *)malloc(LEN)这句行吗,

不可以,因为P2实质上起一个临时指针的作用,用它的遍历来创建链表,这句话应该这样看
p1=(struct student *)malloc(LEN)
p2=p1这一句是很重要的,因为下面有p2->next=p1