C中链表的链表

a linked list of linked lists in C

我正在做一个项目,想知道我是否可以创建一个链表的链表。 我想在 C 中创建一个新类型 person,其中每个 person 可以有 kidskidsperson 的列表,而且每个 person 都有 parents 也是 persons.So 我正在考虑使用结构和链表来做到这一点。

#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;
}; 

提前感谢您的宝贵时间。

是的,您可以列出清单,下面显示了一个示例,children 的清单每个都有自己的玩具清单。

首先是object两种类型(children和玩具)的相关头文件和结构:

#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;
}

接下来,辅助函数分配object的两种类型并将它们插入到相关列表中。请注意,我在列表的开头插入以简化代码,因此我们不必担心列表遍历或存储最终项目指针。

这意味着在转储详细信息时,所有内容都将以相反的顺序打印,但为了保持简单,这是一个很小的代价:

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