Linux中的内核链表
  eVzzROmRiJco 2023年11月19日 18 0

了解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"
    }
]

注意:keytypeval都需要保存到链表节点中去,val上述例子描述是字符串,但是实际存储的时候需要根据type的类型进行变化(这里不用判断,直接按照逻辑赋值即可)。遍历输出时候,也要根据相应的类型进行变化输出(遍历过程中需要判断,然后根据类型进行相应的输出)。

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月19日 0

暂无评论

推荐阅读
  eVzzROmRiJco   2023年11月19日   19   0   0 linux
  zLxnEsMLk4BL   2023年11月19日   29   0   0 变量名字符串bclinux
  DF5J4hb0hcmT   2023年11月12日   25   0   0 linux
  eVzzROmRiJco   2023年11月19日   19   0   0 内核链表linux
eVzzROmRiJco