如何使用sys / queue.h中的列表?

问题描述 投票:24回答:1

目前,我已经实现了一个单链表,如下所示:

struct PeerNode {
     struct Peer* cargo;
     struct PeerNode* next;
};

...我有一个包含几个链接列表的结构,如下所示:

struct Torrent {
     ...
     struct PeerNode* peer_list;
     struct PeerNode* unchoked_peers;
     ...
}

我想通过使用sys/queue.h提供的宏来替换它。我知道我可以用这样的代码替换我的代码:

struct Torrent {
     ...
     LIST_ENTRY(PeerNode, Peer) peer_list;
     struct PeerNode* unchoked_peers;
     ...
}

然后,从查看man queue,我相信我会通过这样做来初始化列表:

LIST_INIT(&peer_list);
LIST_INIT(unchoked_peers);

但是,我不明白LIST_ENTRY如何影响列表的使用。从man页面,它说:“宏LIST_ENTRY声明了一个连接列表中元素的结构,”但我真的不明白这意味着什么。

为什么我要声明一个结构来连接列表中的元素?不应该通过指针将每个节点连接到下一个节点,就像我的初始链表实现一样?如何用sys/queue.h提供的实现替换我的链表?如何在列表中插入元素?

c linux list bsd
1个回答
33
投票

LIST_ENTRY创建了适合链接元素的结构字段,因此您不必关心这些指针的细节。

struct foo {
    int a, b, c;
    /* This is instead of "struct foo *next" */
    LIST_ENTRY(foo) pointers;
};

然后创建一个列表,您将使用LIST_HEAD():

struct Torrent {
    LIST_HEAD(foo_list, foo) bar;
};

您可以使用LIST_INIT()初始化列表标题:

struct Torrent t;
LIST_INIT(&t.bar);

您可以使用LIST_INSERT _ *()宏插入元素:

struct foo *item = malloc(sizeof(struct foo));
LIST_INSERT_HEAD(&t.bar, item, pointers);

这完全取自http://www.manpagez.com/man/3/queue/手册页中的列表示例

© www.soinside.com 2019 - 2024. All rights reserved.