C语言链表创建

#include "malloc.h"
#include "stdio.h"
#define LEN sizeof(struct student)

typedef struct student
{
int num;
int age;
float score;
struct student *next;
}stu;
int n;
// 创建动态链表函数
stu *creat(void)
{
//定义结构体类型的指针
stu *head,*p1,*p2;
n=0;
p1=p2=(stu *)malloc(LEN);//开辟一个内存空间
// 输入结构体类型的数据
scanf("%d,%d,%f",&p1->num,&p1->age,&p1->score);
head=NULL;
while(p1->num!=0)
{
n=n+1;
if (n==1)head=p1;
else
// 单向链表
p2->next=p1;
p2=p1;
p1=(stu *)malloc(LEN);
scanf("%d,%d,%f",&p1->num,&p1->age,&p1->score);
}
p2->next=NULL;
return(head);
}
main()
{
stu *p,*head;
head=creat();
if (head!=NULL)
{
do
{
printf("%d,%d,%f\n",p->num,p->age,p->score);
p=p->next;
}while(p!=NULL);
}
return 0;
}

猜你喜欢

转载自www.cnblogs.com/tudapao/p/9021055.html