【C语言】用结构体实现动态单链表

源代码

#include<stdio.h>
#include<string.h>
#include<stdlib.h>//使用 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 头文件。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值