[软件资料] 无数据域双向链表代码

[复制链接]
945|8
 楼主| jf101 发表于 2024-3-26 17:00 | 显示全部楼层 |阅读模式

下面是一个简单的示例,演示了如何使用无数据域双向链表进行插入和访问操作:


  1. #include <stdio.h>
  2. #include <stddef.h> // 包含offsetof宏

  3. // 定义节点结构体
  4. struct Node
  5. {
  6.     struct Node* prev;
  7.     struct Node* next;
  8. };

  9. // 定义测试结构体
  10. struct Data
  11. {
  12.     int data;
  13.     struct Node list;
  14. };

  15. // 插入节点到链表尾部
  16. void insert(struct Node* head, struct Node* newNode)
  17. {
  18.     struct Node* current = head;

  19.     while (current->next != NULL)
  20.     {
  21.         current = current->next;
  22.     }

  23.     newNode->prev = current;
  24.     newNode->next = NULL;
  25.     current->next = newNode;
  26. }

  27. // 打印链表内容
  28. void printList(struct Node* head)
  29. {
  30.     printf("List: ");
  31.     struct Node* current = head->next;

  32.     while (current != NULL)
  33.     {
  34.         // 通过偏移量找到Test结构体的地址
  35.      struct Data* test = (struct Data*)((char*)current - offsetof(struct Data, list));

  36.         printf("%d -> ", test->data);
  37.         current = current->next;
  38.     }

  39.     printf("NULL\n");
  40. }

  41. int main()
  42. {
  43.     // 创建链表头节点
  44.     struct Node head;
  45.     head.prev = NULL;
  46.     head.next = NULL;

  47.     // 创建并插入节点
  48.     struct Data test1 = {1, {NULL, NULL}};
  49.     struct Data test2 = {2, {NULL, NULL}};
  50.     struct Data test3 = {3, {NULL, NULL}};

  51.     // 插入节点到链表
  52.     insert(&head, &test1.list);
  53.     insert(&head, &test2.list);
  54.     insert(&head, &test3.list);

  55.     // 打印链表内容
  56.     printList(&head);

  57.     return 0;
  58. }


在这个示例中,我们定义了一个包含指向前一个节点和后一个节点的结构体 Node,以及一个包含整数数据和 Node 结构体的结构体 Data。然后实现了插入和打印链表的函数。在打印链表内容的函数中,通过 offsetof 宏获取 Data 结构体中 listNode 成员的偏移量,从而得到节点所在的地址,进而访问节点中存储的数据。

通过这个示例,我们可以看到如何使用无数据域双向链表进行插入和访问操作,以及如何使用 offsetof 宏来方便地获取结构体中成员的偏移量。
中国龙芯CDX 发表于 2024-4-10 11:12 | 显示全部楼层
这个示例,我们可以看到如何使用无数据域双向链表进行插入和访问操作,非常适合新手学习
小夏天的大西瓜 发表于 2024-4-10 13:40 | 显示全部楼层
使用 offsetof 宏来方便地获取结构体中成员的偏移量
szt1993 发表于 2024-4-10 17:15 | 显示全部楼层
链表的样例属具,方便获取结构体偏移量
 楼主| jf101 发表于 2024-4-14 15:41 | 显示全部楼层
中国龙芯CDX 发表于 2024-4-10 11:12
这个示例,我们可以看到如何使用无数据域双向链表进行插入和访问操作,非常适合新手学习 ...

是的
 楼主| jf101 发表于 2024-4-14 15:41 | 显示全部楼层
szt1993 发表于 2024-4-10 17:15
链表的样例属具,方便获取结构体偏移量

链表其实是指针的一种实例化
小小蚂蚁举千斤 发表于 2024-4-15 09:43 | 显示全部楼层
无数据域双向链表进行插入和访问操作是最基本的操作
OKAKAKO 发表于 2024-4-19 18:50 | 显示全部楼层
使用无数据域双向链表进行插入和访问操作的例子很实用
星辰大海不退缩 发表于 2024-4-21 11:36 | 显示全部楼层
使用 offsetof 宏来方便地获取结构体中成员的偏移量
您需要登录后才可以回帖 登录 | 注册

本版积分规则

264

主题

2029

帖子

3

粉丝
快速回复 在线客服 返回列表 返回顶部