了解Linux内核链表
Linux内核中的链表
https://www.cnblogs.com/wangzahngjun/p/5556448.html
DEMO实例
#include <stdio.h>
#include <string.h>
#include "list.h"
struct student
{
int age;
char name[64];
struct list_head list;
};
void main()
{
struct list_head head;
INIT_LIST_HEAD(&head);
struct student stu1;
strcpy(stu1.name, "zhangsan");
stu1.age = 1;
struct student stu2;
strcpy(stu2.name, "lisi");
stu2.age = 2;
struct student stu3;
strcpy(stu3.name, "wangwu");
stu3.age = 3;
list_add(&stu1.list, &head);
list_add(&stu2.list, &head);
list_add(&stu3.list, &head);
struct list_head *pos;
struct student *tmp;
printf("init list\n");
list_for_each(pos, &head) //这里万万不可加分号
{
tmp = list_entry(pos, struct student, list);
printf("name = %s, age = %d\n", tmp->name, tmp->age);
}
printf("\n");
pos = get_first(&head);
tmp = list_entry(pos, struct student, list);
printf("first is %s\n\n", tmp->name);
pos = get_last(&head);
tmp = list_entry(pos, struct student, list);
printf("last is %s\n\n", tmp->name);
puts("del last");
list_del(pos);
printf("after del:");
list_for_each(pos, &head)
{
tmp = list_entry(pos, struct student, list);
printf("%d ", tmp->age);
}
puts("\n");
}
练习
将下面的数据节点信息转换为链表结构,并遍历输出。要求根据type的值来决定val的类型。type为1代表bool类型,2代表整形,3代表浮点型。无需解析文本,直接赋值形成节点即可。
"data":
[
{
"key": 1,
"type": 2,
"val": "10"
},
{
"key": 2,
"type": 1,
"val": "0"
},
{
"key": 3,
"type": 3,
"val": "22.5"
}
]
注意:key
、type
和val
都需要保存到链表节点中去,val上述例子描述是字符串,但是实际存储的时候需要根据type的类型进行变化(这里不用判断,直接按照逻辑赋值即可)。遍历输出时候,也要根据相应的类型进行变化输出(遍历过程中需要判断,然后根据类型进行相应的输出)。