Linux 如何使用 sys/queue.h 中的列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7627099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use list from sys/queue.h?
提问by rps
Currently, I have implemented a singly linked list, like so:
目前,我已经实现了一个单链表,如下所示:
struct PeerNode {
struct Peer* cargo;
struct PeerNode* next;
};
...and I have a struct that contains a couple of these linked lists, like so:
...我有一个包含几个这样的链表的结构,如下所示:
struct Torrent {
...
struct PeerNode* peer_list;
struct PeerNode* unchoked_peers;
...
}
I would like to replace this by using the macros provided by sys/queue.h
. I gather that I could replace my code with something like this:
我想通过使用提供的宏来替换它sys/queue.h
。我认为我可以用这样的东西替换我的代码:
struct Torrent {
...
LIST_ENTRY(PeerNode, Peer) peer_list;
struct PeerNode* unchoked_peers;
...
}
Then, from looking at man queue
, I believe I would initialize the lists by doing something like this:
然后,从查看man queue
,我相信我会通过执行以下操作来初始化列表:
LIST_INIT(&peer_list);
LIST_INIT(unchoked_peers);
However, I don't understand how LIST_ENTRY
factors into usage of the list. From the man
page, it says: "The macro LIST_ENTRY
declares a structure that connects the elements in the list," but I don't really understand what this means.
但是,我不明白如何LIST_ENTRY
影响列表的使用。从man
页面上看,它说:“宏LIST_ENTRY
声明了一个连接列表中元素的结构”,但我真的不明白这是什么意思。
Why would I want to declare a structure to connect the elements in the list? Shouldn't each node be connected to the next node via a pointer, like my initial linked list implementation? How would I replace my linked lists with the implementation provided by sys/queue.h
? How would I insert an element into the list?
为什么我要声明一个结构来连接列表中的元素?每个节点不应该通过指针连接到下一个节点,就像我最初的链表实现一样吗?我将如何用提供的实现替换我的链表sys/queue.h
?如何在列表中插入元素?
采纳答案by tinman
LIST_ENTRY creates fields to put into your structure that are suitable for linking the elements, so you do not have to concern yourself with the specifics of those pointers.
LIST_ENTRY 创建要放入适合链接元素的结构的字段,因此您不必关心这些指针的细节。
struct foo {
int a, b, c;
/* This is instead of "struct foo *next" */
LIST_ENTRY(foo) pointers;
};
To then create a list you'd use LIST_HEAD():
然后创建一个列表,您将使用 LIST_HEAD():
struct Torrent {
LIST_HEAD(foo_list, foo) bar;
};
You can initialise the list header using LIST_INIT():
您可以使用 LIST_INIT() 初始化列表头:
struct Torrent t;
LIST_INIT(&t.bar);
You can insert elements using the LIST_INSERT_*() macros:
您可以使用 LIST_INSERT_*() 宏插入元素:
struct foo *item = malloc(sizeof(struct foo));
LIST_INSERT_HEAD(&t.bar, item, pointers);
This was all taken from the list example in the man pages at http://www.manpagez.com/man/3/queue/
这全部取自http://www.manpagez.com/man/3/queue/手册页中的列表示例