c语言链表的创建

链表的优点1.可以随时利用指针读取

                   2.方便对于链表中数据的修改

 基本结构组成:指针;一定的结构体(我又称基本结构体)

struct stu{
int num;//数据域
struct stu *next;//指针域(注意指针域的格式)指向该结构体的指针。
}

需要的基本操作: 内存动态管理

                         分配内存空间函数malloc

void *malloc(unsigned int size);功能是在内存的动态存储区中分配一块长度为size的连续区域。如果分配成功,返回值为该区域的首地址。

首先创建链表需要1读取数据;2生成新节点;3将数据存入新节点;4将新节点插入链表中

#include<stdio.h>
#include<malloc.h>//引用malloc的库文件
#define LEN sizeof(struct stu)//LEN为结构体类型structuralstu 的长度
struct stu {
	int num;
	float score;
	struct stu *next;//注意该指针的类型标识符
};
struct stu *creat() {
	struct stu *head;//
	struct stu *p;//指向新区域的指针
	struct stu *tail;//在这个过程中tail有两个作用1.用于中间转换的指针2.作为尾指针
	int x;
	tail = head = NULL;//指针要初始化
	scanf_s("%d", &x);
	while (x != 0)   //多个链表要用多个链表域实现(这里循环语句可以实现)
	{
		p = (struct stu *)malloc(LEN);
		p->num = x;//数据域赋值
		if (head == NULL) head = p;//将第一个链表作为首链表并作为整个链表的首地址
		scanf_s("%f", &p->score);
		if (tail != NULL) tail->next = p;//将新的节点作为链表尾巴来实现链接,依次通过循环语句来使单个链结形成一个长连接。
		tail = p;//这一步,是为了上一行做铺垫
		scanf_s("%d", &x);
	}
	if (tail != NULL) tail->next = NULL;//最后一个节点的 指针域为NULL
	return(head);
}
void list(struct stu *head) {
	struct stu *p;
	p = head;
	if (head != NULL) {
		printf("the list records are :\n");
		do //利用循环语句来实习链表的输出。
		{
			printf("%d\t%5.1f\n", p->num, p->score);
			p = p->next;

		} while (p != NULL);
	}
	else
		printf("the list is null");

}
main() {
	struct stu *head;
	head = creat();
	list(head);
	return 0;
}

第一次发博客希望大佬不吝啬指教,若有错误请指出。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值