下面是一个简单的示例,演示了如何使用无数据域双向链表进行插入和访问操作:
- #include <stdio.h>
- #include <stddef.h> // 包含offsetof宏
- // 定义节点结构体
- struct Node
- {
- struct Node* prev;
- struct Node* next;
- };
- // 定义测试结构体
- struct Data
- {
- int data;
- struct Node list;
- };
- // 插入节点到链表尾部
- void insert(struct Node* head, struct Node* newNode)
- {
- struct Node* current = head;
- while (current->next != NULL)
- {
- current = current->next;
- }
- newNode->prev = current;
- newNode->next = NULL;
- current->next = newNode;
- }
- // 打印链表内容
- void printList(struct Node* head)
- {
- printf("List: ");
- struct Node* current = head->next;
- while (current != NULL)
- {
- // 通过偏移量找到Test结构体的地址
- struct Data* test = (struct Data*)((char*)current - offsetof(struct Data, list));
- printf("%d -> ", test->data);
- current = current->next;
- }
- printf("NULL\n");
- }
- int main()
- {
- // 创建链表头节点
- struct Node head;
- head.prev = NULL;
- head.next = NULL;
- // 创建并插入节点
- struct Data test1 = {1, {NULL, NULL}};
- struct Data test2 = {2, {NULL, NULL}};
- struct Data test3 = {3, {NULL, NULL}};
- // 插入节点到链表
- insert(&head, &test1.list);
- insert(&head, &test2.list);
- insert(&head, &test3.list);
- // 打印链表内容
- printList(&head);
- return 0;
- }
在这个示例中,我们定义了一个包含指向前一个节点和后一个节点的结构体 Node,以及一个包含整数数据和 Node 结构体的结构体 Data。然后实现了插入和打印链表的函数。在打印链表内容的函数中,通过 offsetof 宏获取 Data 结构体中 listNode 成员的偏移量,从而得到节点所在的地址,进而访问节点中存储的数据。
通过这个示例,我们可以看到如何使用无数据域双向链表进行插入和访问操作,以及如何使用 offsetof 宏来方便地获取结构体中成员的偏移量。
|