How to use list from sys/queue.h?

后端 未结 1 1700
天涯浪人
天涯浪人 2021-01-31 18:12

Currently, I have implemented a singly linked list, like so:

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

...and I

相关标签:
1条回答
  • 2021-01-31 18:35

    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.

    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():

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

    You can initialise the list header using LIST_INIT():

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

    You can insert elements using the LIST_INSERT_*() macros:

    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/

    For a full example: http://infnis.wikidot.com/list-from-sys-queue-h

    0 讨论(0)
提交回复
热议问题