c语言链表的创建_m0
链表的优点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 :
");
- do //利用循环语句来实习链表的输出。
- {
- printf("%%d %%5.1f
", 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;
- }
第一次发博客希望大佬不吝啬指教,若有错误请指出。
推荐阅读