当前位置:   article > 正文

C语言中常用宏

C语言中常用宏

记录一些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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/942149
推荐阅读
相关标签
  

闽ICP备14008679号