c语言queue--数据域与指针域分开

本文介绍了一种队列数据结构的实现方式,并提供了一个简单的示例程序。该程序使用自定义的数据结构实现了队列的基本操作,如入队、出队等,并通过一个具体的例子展示了如何使用这些函数来操作队列。

实现:

#ifndef HO_QUEUE_H
#define HO_QUEUE_H

#include <stdlib.h>
#undef offsetof
struct queue_head {
    struct queue_node *head;
    struct queue_node *tail;
};

struct queue_node {
    struct queue_node *next;
};

#define QUEUE_HEAD_INIT {.head = NULL, .tail = NULL}
#define INIT_QUEUE_HEAD(ptr) do {\
    (ptr)->head = NULL;(ptr)->tail = NULL; \
} while (0)

#define offsetof(type, member) ((size_t)&((type *)0)->member)
#define queue_entry(ptr, type, member) (type *)((char *)ptr - offsetof(type, member))

static inline void queue_put(struct queue_node *n, struct queue_head *h) {
    n->next = NULL;
    if (!h->head) {
        h->head = h->tail = n;
    } else {
        h->tail->next = n;
        h->tail = n;
    }
}

static inline struct queue_node *queue_get(struct queue_head *h) {
    struct queue_node *t = h->head;
    h->head = h->head ? h->head->next: NULL;
    return t;
}

static inline int queue_empty(struct queue_head *h) {
    return !h->head;
}

#define queue_for_each(pos, h) \
    for(pos = (h)->head; pos; pos = pos->next)
#endif


如何使用:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "queue.h"

struct queue_node2 {
    void *data;
    struct queue_node queue;
};

int main() {

    struct queue_head head = QUEUE_HEAD_INIT;
    struct queue_node *pos;
    struct queue_node2 *tmp;

    tmp = malloc(sizeof(struct queue_node2));
    tmp->data = strdup("aaaaaaaaaaaaaaa");
    queue_put(&tmp->queue, &head);

    tmp = malloc(sizeof(struct queue_node2));
    tmp->data = strdup("bbbbbbbbbbbbbbb");
    queue_put(&tmp->queue, &head);

    tmp = malloc(sizeof(struct queue_node2));
    tmp->data = strdup("ccccccccccccccc");
    queue_put(&tmp->queue, &head);

    tmp = malloc(sizeof(struct queue_node2));
    tmp->data = strdup("ddddddddddddddd");
    queue_put(&tmp->queue, &head);

#if 0
    queue_for_each(pos, &head) {
        tmp = queue_entry(pos, struct queue_node2, queue);
        printf("%s\n", (char *)tmp->data);
    }
#endif

    while (!queue_empty(&head)) {
        pos = queue_get(&head);
        tmp = queue_entry(pos, struct queue_node2, queue);
        printf("%s\n", (char *)tmp->data);
        free(tmp->data);
        free(tmp);
    }

    return 0;
}


转载于:https://my.oschina.net/guonaihong/blog/276751

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值