C语言中常用宏

发布于:2024-08-08 ⋅ 阅读:(67) ⋅ 点赞:(0)

记录一些C语言常用到的一些经典的宏

TAILQ_HEAD 双向链表

#include <stdio.h>
#include <stdlib.h>
#include <sys/queue.h>

// 定义一个队列元素结构
struct entry {
    int value;
    TAILQ_ENTRY(entry) entries; // 定义链表指针字段
};

// 定义一个队列头结构
TAILQ_HEAD(tailhead, entry);

int main() {
    // 初始化队列头
    struct tailhead head;
    TAILQ_INIT(&head);

    // 插入元素到队列尾部
    struct entry *elem1 = malloc(sizeof(struct entry));
    elem1->value = 10;
    TAILQ_INSERT_TAIL(&head, elem1, entries);

    struct entry *elem2 = malloc(sizeof(struct entry));
    elem2->value = 20;
    TAILQ_INSERT_TAIL(&head, elem2, entries);

    struct entry *elem3 = malloc(sizeof(struct entry));
    elem3->value = 30;
    TAILQ_INSERT_TAIL(&head, elem3, entries);

    // 遍历队列中的每个元素
    struct entry *elem;
    printf("队列中的元素:\n");
    TAILQ_FOREACH(elem, &head, entries) {
        printf("%d\n", elem->value);
    }

    // 获取第一个元素
    struct entry *first = TAILQ_FIRST(&head);
    if (first) {
        printf("第一个元素: %d\n", first->value);
    }

    // 获取下一个元素
    struct entry *next = TAILQ_NEXT(first, entries);
    if (next) {
        printf("第二个元素: %d\n", next->value);
    }

    // 获取最后一个元素
    struct entry *last = TAILQ_LAST(&head, tailhead);
    if (last) {
        printf("最后一个元素: %d\n", last->value);
    }

    // 从队列中移除一个元素
    printf("移除元素: %d\n", elem2->value);
    TAILQ_REMOVE(&head, elem2, entries);
    free(elem2);

    // 再次遍历队列中的每个元素
    printf("移除后的队列:\n");
    TAILQ_FOREACH(elem, &head, entries) {
        printf("%d\n", elem->value);
    }

    // 释放剩余的元素
    while ((elem = TAILQ_FIRST(&head)) != NULL) {
        TAILQ_REMOVE(&head, elem, entries);
        free(elem);
    }

    return 0;
}

网站公告

今日签到

点亮在社区的每一天
去签到