源代码
#include
#include
#include//使用 malloc 需要引入 stdlib.h 头文件
#define NUM 3
typedef struct Students//定义 Students 链表
{
int num;
int score;
Students *next; //指向下一个元素的指针
}Students;
int main()
{
//建立动态链表
Students *head,*p1,*p2;
p1=(Students *)malloc(sizeof(Students));//开辟内存空间
//键入数据
printf("请输入学号:");
scanf("%d",&p1->num);
//fflush(stdin); //由于是输入 int 类型,所以无需清空输入流
printf("\n");
printf("请输入成绩:");
scanf("%d",&p1->score);
printf("\n");
head=p1;//将p1定义为头元素
do
{
p2=(Students *)malloc(sizeof(Students));//开辟内存空间
//键入数据,存入p2
printf("请输入学号:");
scanf("%d",&p2->num);
printf("\n");
if(p2->num==0)
{
printf("退出输入!\n\n");
break;
}
printf("请输入成绩:");
scanf("%d",&p2->score);
printf("\n");
p1->next=p2;
p1=p2;
}while(p2->num!=0);
//输出链表
puts("学号 成绩");
do
{
printf("%d %d\n",head->num,head->score);
head=head->next;
}while(head!=NULL);
return 0;
}
结果:
注
1.嵌套声明结构体类型,并用 typedef 重命名时,必须声明结构体的名字,如下:
typedef struct Students
{
int num;
int score;
struct Students *next;// 或 Students *next;
}Students;
而不能这样:
typedef struct
{
int num;
int score;
Students *next;
}Students;
2.使用 malloc 函数需要引入 stdlib.h 头文件。