c - glibc - 列表和其他数据结构实现

标签 c linux list glibc

我觉得我的谷歌搜索技能现在很差,找不到 glibc 中的列表实现,找到了 hashtree实现,但不是列表。

是否有任何 glibc 实现?我不想重新格式化 linux kernel linked list宏并在用户空间中使用它们。

最佳答案

/usr/include/sys/queue.h 包含各种链表变体。(超过 man page 文档)

这是一个 TAIL_QUEUE 的例子: 通过预处理器 (gcc -E -c prog.c) 运行它以更容易地查看它是如何运行的 在引擎盖下工作)

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



struct Block {
    char text[64];
    //linked list entry
    TAILQ_ENTRY(Block) blocks;
};
struct File {
   char name[128];
   //list of blocks in the "file"
   TAILQ_HEAD(,Block) head; 
};


void add_block(struct File *f, const char *txt)
{
   struct Block *b = malloc(sizeof *b);
   strcpy(b->text,txt); 
   TAILQ_INSERT_TAIL(&f->head, b, blocks);
}

void print_file(struct File *f)
{
    struct Block *b;
    printf("File: %s\n", f->name);
    TAILQ_FOREACH(b, &f->head, blocks) {
        printf("Block: %s\n", b->text);
    }
}
void delete_block(struct File *f, const char *txt)
{
    struct Block *b, *next;
    for(b = TAILQ_FIRST(&f->head) ; b != NULL ; b = next) {
        next = TAILQ_NEXT(b, blocks);
        if(strcmp(b->text, txt) == 0) {
            TAILQ_REMOVE(&f->head, b, blocks);
            free(b);
        }
    }

}

void delete_all_blocks(struct File *f)
{
    struct Block *b;
    while((b = TAILQ_FIRST(&f->head))) {
        TAILQ_REMOVE(&f->head, b, blocks);
        free(b);
    }
}

int main(void)
{
    struct File f;
    TAILQ_INIT(&f.head);
    strcpy(f.name,"Test.f");
    add_block(&f,"one");
    add_block(&f,"two");
    add_block(&f,"three");

    print_file(&f);

    puts("\nDeleting three");
    delete_block(&f, "three");
    print_file(&f);

    puts("\nAdding 2 blocks");
    add_block(&f,"three");
    add_block(&f,"three");
    print_file(&f);

    puts("\nDeleting three");
    delete_block(&f, "three");
    print_file(&f);

    delete_all_blocks(&f);


    return 0;
}

关于c - glibc - 列表和其他数据结构实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16819910/

相关文章:

c - 让 gdb 在成功终止时自动退出?

python - 如何为一长串整数创建优化的迭代器?

c# - 将类型的通用容器转换为继承类型的容器?

c - 为什么 GCC 不优化求和循环中的内存写入?

c - RAM & ROM 内存段

c - 分配内存时出现错误 "initializer element is not constant"

python - 字符串的一个热编码列表

c++ - 我们什么时候需要在 c 中进行深度复制

linux - 未绑定(bind) DNS 的 NetworkManager

c - Linux 堆碎片