簡體   English   中英

glibc - 列表和其他數據結構實現

[英]glibc - list and other data structures implementations

我填寫像我的谷歌搜索技能現在很差,找不到glibc中的列表實現,找到哈希實現但不是列表之一。

是否有任何glibc實現? 我不想重新格式化linux內核鏈表宏並在用戶空間中使用它們。

你可以使用insque(3)remque(3)

/usr/include/sys/queue.h包含各種鏈表變體。(超過手冊頁文檔)

以下是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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM