一个链表的小问题
代码是创建一个链表,输入0的时候结束创建
while(p2->num!=0)
{
n=n+1;
if(n==1)
{
head=p1;
}
else
{
p1->next=p2; ///////// 最后输入 0 之后,没有执行这里!!
p1=p2;
p2=(struct Student*)malloc(LEN);
scanf("%d",&p2->num);
}
}
p2->next=NULL;//将这里的p2改成p1之后就没事了
struct Student* creat()
{
struct Student *p1,*p2,*head;
p1=p2=(struct Student*)malloc(LEN);
scanf("%d",&p2->num);
head=NULL; //这里为什么还要把head给NULL一下?
while(p2->num!=0)
{
p1->next=p2;
p1=p2;
p2=(struct Student*)malloc(LEN);
scanf("%d",&p2->num);
p1->next = p2->next,但是,p2经过malloc且while循环不再执行后,p1->next指向哪里?这就造成了野指针。