建立一个存放学生数据的动态链表
#include <stdio.h>
#include <stdlib.h>
//定义一个常量LEN,用来表示一个结构体的长度
#define LEN sizeof(struct Student)
//声明一个结构体,包括学生编号,成绩,以及一个和该结构体相同基类型的指针变量
struct Student
{
long num;
float score;
struct Student *next;
}; //分号不能少
int n;//记录节点数
//声明creat方法,返回值是基类型为struct Student的指针
struct Student *creat()
{
struct Student *head,*p1,*p2;
n=0;
/*
在内存中开辟一段长度为LEN的动态存储区,强制类型转换为struct Student *类型(也可自动类型转换),
使malloc返回的指针转换为指向struct Student类型数据的指针。
并且让p1,p2指向这块内存空间
*/
p1=p2=(struct Student *) malloc(LEN);
printf("请输入学生编号,学生成绩:\n");
//把输入的编号和成绩放在p1所指向的内存空间中
scanf("%ld,%f",&p1->num,&p1->score);
head=NULL;
//当输入的编号为不为0时,执行循环
while(p1->num!=0)
{
n+=1;
//n为1表示是第一个节点
if(n==1)
{
//让头指针指向第一个节点
head=p1;
}else
{
//如果输入的不是第一个节点,让p2指向的节点的next变量指向p1指向的节点
p2->next=p1;
}
//让p2指向p1所指向的节点
p2=p1;
//新开辟一个空间,让p1指向它
p1=(struct Student *) malloc(LEN);
scanf("%ld,%f",&p1->num,&p1->score);
}
//给p2指向节点的next变量赋值为NULL,表示这是最后一个节点
p2->next=NULL;
//返回头指针
return(head);
}
int main()
{
struct Student *pt;
pt=creat(); //调用creat方法,返回的地址用pt接收
printf("\nnum:%ld\nscore:%5.1f\n",pt->num,pt->score);
return 0;
}
运行结果如下:![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c618fb6a512b17f8b17ce6fd9891a0a3.png)