c - C中链表的链表

标签 c linked-list

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

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

提前感谢您的宝贵时间。

最佳答案

是的,您可以有列表的列表,下面显示了一个示例,一个 child 列表,每个 child 都有自己的玩具列表。

首先是两类对象( child 和玩具)的相关头文件和结构:

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

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

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

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

关于c - C中链表的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27768334/

相关文章:

c - C中的Seg故障链表递归

C 链表临时变量

c - 无法在Linux中使用C创建链表

C:访问第 i 个可变参数

c - 从http套接字中提取位置

c - 在 Linux 上用 C 流式传输音频文件

java - Java 中链表的递归最大值

c - 使用快速排序对带有指针的数组进行排序

c - C 中的文件 I/O - 如何从文件读取然后写入文件?

c - 我在 C 程序中遇到运行时错误,该错误应该从中缀表示法转换为后缀表示法