家族家谱树数据结构代码C语言
时间: 2023-07-07 22:05:48 浏览: 435
数据结构家族谱管理系统C语言源代码
以下是一个简单的家族家谱树的数据结构代码,使用了链式存储结构:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
char name[20];
struct node *father, *mother, *spouse, *child;
} Node;
Node *createNode(char *name) {
Node *newNode = (Node *)malloc(sizeof(Node));
strcpy(newNode->name, name);
newNode->father = NULL;
newNode->mother = NULL;
newNode->spouse = NULL;
newNode->child = NULL;
return newNode;
}
void addChild(Node *parent, Node *child) {
child->father = parent;
if (parent->child == NULL) {
parent->child = child;
} else {
Node *cur = parent->child;
while (cur->spouse != NULL) {
cur = cur->spouse;
}
cur->spouse = child;
}
}
void printFamilyTree(Node *root, int level) {
int i;
for (i = 0; i < level; i++) {
printf(" ");
}
printf("%s\n", root->name);
Node *cur = root->child;
while (cur != NULL) {
printFamilyTree(cur, level + 1);
cur = cur->spouse;
}
}
int main() {
Node *root = createNode("Adam");
Node *eve = createNode("Eve");
addChild(root, eve);
Node *cain = createNode("Cain");
addChild(eve, cain);
Node *abel = createNode("Abel");
addChild(eve, abel);
Node *seth = createNode("Seth");
addChild(eve, seth);
Node *enosh = createNode("Enosh");
addChild(seth, enosh);
Node *kenan = createNode("Kenan");
addChild(seth, kenan);
Node *mahalalel = createNode("Mahalalel");
addChild(seth, mahalalel);
Node *jared = createNode("Jared");
addChild(seth, jared);
Node *enoch = createNode("Enoch");
addChild(seth, enoch);
Node *methuselah = createNode("Methuselah");
addChild(seth, methuselah);
Node *lamach = createNode("Lamach");
addChild(seth, lamach);
Node *noah = createNode("Noah");
addChild(lamach, noah);
printFamilyTree(root, 0);
return 0;
}
```
输出结果:
```
Adam
Eve
Cain
Abel
Seth
Enosh
Kenan
Mahalalel
Jared
Enoch
Methuselah
Lamach
Noah
```
阅读全文