簡體   English   中英

C中鏈接列表的鏈接列表

[英]a linked list of linked lists in C

我正在做一個項目,想知道是否可以創建鏈接列表的鏈接列表。 我想用C創建一個新型的 ,每個都可以有孩子 孩子是一個的列表,每個都有一個父母也是人。因此,我正在考慮使用結構和鏈接列表來做到這一點。

#include <stdio.h>

struct person {
unsigned int id;    //identity,unique for every person
char* name;
struct person **father;
struct person **mother;
struct kids **kids;
}

struct kids {
struct person **kid;
struct kids **next_kid;
}; 

預先感謝您的寶貴時間。

是的,您可以擁有一個列表列表,下面顯示了一個示例,每個孩子都有自己的玩具列表。

首先,兩種對象(兒童和玩具)的相關頭文件和結構:

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

typedef struct sToy {
    char name[50];
    struct sToy *next;
} tToy;

typedef struct sChild {
    char name[50];
    tToy *firstToy;
    struct sChild *next;
} tChild;

然后,一個用於分配內存的輔助函數,這樣我就不必通過大量錯誤檢查來污染樣本了:

void *chkMalloc (size_t sz) {
    void *mem = malloc (sz);

    // Just fail immediately on error.

    if (mem == NULL) {
        printf ("Out of memory! Exiting.\n");
        exit (1);
    }

    // Otherwise we know it worked.

    return mem;
}

接下來,helper函數分配兩種類型的對象並將它們插入相關列表中。 請注意,我將在列表的開頭插入以簡化代碼,因此我們不必擔心列表遍歷或存儲最終項目指針。

這意味着在轉儲細節時,所有內容都將以相反的順序打印,但這對於保持簡單性來說是一個很小的代價:

void addChild (tChild **first, char *name) {
    // Insert new item at start.

    tChild *newest = chkMalloc (sizeof (*newest));
    strcpy (newest->name, name);
    newest->next = *first;
    *first = newest;
}

void addToy (tChild *first, char *name) {
    // Insert at start of list.

    tToy *newest = chkMalloc (sizeof (*newest));
    strcpy (newest->name, name);
    newest->next = first->firstToy;
    first->firstToy = newest;
}

接下來,以可讀格式轉儲列表的功能:

void dumpDetails (tChild *currChild) {
    // For every child.

    while (currChild != NULL) {
        printf ("%s has:\n", currChild->name);

        // For every toy that child has.

        tToy *currToy = currChild->firstToy;
        if (currToy == NULL) {
            printf ("   <<nothing>>\n");
        } else {
            while (currToy != NULL) {
                printf ("   %s\n", currToy->name);
                currToy = currToy->next;
            }
        }
        currChild = currChild->next;
    }
}

最后,還有一個主要功能,可將所有其他功能捆綁在一起:

int main (void) {
    tChild *firstChild = NULL;

    addChild (&firstChild, "Anita");
        addToy (firstChild, "skipping rope");
    addChild (&firstChild, "Beth");
    addChild (&firstChild, "Carla");
        addToy (firstChild, "model car");
        addToy (firstChild, "trampoline");

    dumpDetails (firstChild);

    return 0;
}

輸入,編譯和運行所有代碼后,您會發現它很容易處理列表列表:

Carla has:
   trampoline
   model car
Beth has:
   <<nothing>>
Anita has:
   skipping rope

暫無
暫無

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

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