我正在制作一个项目,并想知道我是否可以创建一个链表的链表。 我想在C中创建一个新类型的人 ,每个人都可以有孩子 。 孩子是一个人的名单,每个人都有父母也是人。所以我想用结构和链表做这件事。
#include 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 #include #include 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; }
接下来,以可读格式转储列表的function:
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 (" <>n"); } else { while (currToy != NULL) { printf (" %sn", currToy->name); currToy = currToy->next; } } currChild = currChild->next; } }
最后,将所有其他人捆绑在一起的主要function:
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: <> Anita has: skipping rope
以上就是c/c++开发分享C中链表的链表相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/549237.html