当前位置: 首页 > 工具软件 > HQueue > 使用案例 >

C语言数据结构(五)-------------------------------HQueue

南宫炜
2023-12-01
#include <stdbool.h>

struct hqueue_head {
    struct hqueue_head *prev;
    struct hqueue_head *next;
};

typedef void (*hqueue_free_node_func) (struct hqueue_head *node);

struct hqueue {
    struct hqueue_head elements;
    hqueue_free_node_func free_func;
};

#define QUEUE_ENTRY(node, type, member) \
    ((type*)((char*)(node) - (size_t)&((type*)0)->member))

#define HQUEUE_IS_EMPTY(hqueue) \
    (hqueue->elements.next == &hqueue->elements)

static inline struct hqueue *hqueue_create(hqueue_free_node_func free_func)
{
    struct hqueue *queue = (struct hqueue *)malloc(sizeof(*queue));
    queue->elements = {&queue->elements, &queue->elements};
    queue->free_func = free_func;
    return queue;
}

static inline void hqueue_free(struct hqueue *queue)
{
    struct hqueue_head *node, *tmp;

    for (node = queue->elements.next, tmp = node->next; 
         node != &queue->elements; node = tmp, tmp = tmp->next) {
        queue->free_func(node);
    }
    return;
}

static inline void hqueue_in(struct hqueue *queue, struct hqueue_head *node)
{
    node->next = queue->elements.next;
    node->prev = &queue->elements;
    queue->elements.next->prev = node;
    queue->elements.next = node;
}

static inline struct hqueue_head *hqueue_out(struct hqueue *queue)
{
    if (HQUEUE_IS_EMPTY(queue))
        return NULL;
    struct hqueue_head *node = queue->elements.prev;
    node->next->prev = node->prev;
    node->prev->next = node->next;
    node->next = NULL;
    node->prev = NULL;
    return node;
}

 

 类似资料: