C链表问题

来源:百度知道 编辑:UC知道 时间:2024/06/05 23:56:58
#include <conio.h>
#include <stdio.h>
#include <malloc.h>
#define NULL 0
struct stu{int age;
int num;
struct stu *next;};
struct stu *creat(int n)
{struct stu *head,*pf,pb;
int i;
pb=(struct stu*)malloc(sizeof(struct stu));
for(i=0;i<n;i++)
{printf("Input the %dth\n",i+1);
scanf("%d%d",&pb->age,&pb->num);
if(i==0)
pf=head=pb;
else pf->next=pb;
pb->next=NULL;
pf=pb;
}
return(head);
}
main ()
{int n=4;
struct stu *p;
p=creat(n);
while(p!=NULL)
{printf("%d\t%d\n",p->age,p->num);
p=p->next;
}
getch();

}
这个链表错在哪里了?我找不出来,请高手帮忙啊

错的地方给你改正了,为什么错写在注释里了

#include <conio.h>
#include <stdio.h>
#include <malloc.h>
#define NULL 0
struct stu{
int age;
int num;
struct stu *next;
};
struct stu *creat(int n)
{
struct stu *head,*pf,*pb; //pb是一个指针;
int i;
for(i=0;i<n;i++)
{
pb=(struct stu*)malloc(sizeof(struct stu)); //每次都要创建所以要放在循环内
printf("Input the %dth\n",i+1);
scanf("%d%d",&pb->age,&pb->num);
if(i==0) pf=head=pb;
else pf->next=pb;
pb->next=NULL;
pf=pb;
}
return(head);
}
main ()
{
int n=4;
struct stu *p;
p=creat(n);
while(p!=NULL)
{
printf("%d\t%d\n",p->age,p->num);
p=p->next;
}
getch();

}

#include <conio.h>
#include <stdio.h>
#include <malloc.h><