数据结构课程设计家谱c语言
时间: 2023-10-26 16:22:29 浏览: 113
好的,以下是一个简单的家谱 C 语言程序设计示例:
```c
#include <stdio.h>
#include <string.h>
#define MAX_NAME_LEN 20 // 最大名字长度
#define MAX_CHILDREN 10 // 每个人最多的孩子数
// 定义结构体,表示一个人
struct Person {
char name[MAX_NAME_LEN];
struct Person *father;
struct Person *mother;
struct Person *children[MAX_CHILDREN];
int num_children;
};
// 创建一个新的人
struct Person *create_person(char *name) {
struct Person *p = (struct Person *)malloc(sizeof(struct Person));
strcpy(p->name, name);
p->father = NULL;
p->mother = NULL;
p->num_children = 0;
return p;
}
// 添加一个孩子
void add_child(struct Person *parent, struct Person *child) {
if (parent->num_children >= MAX_CHILDREN) {
printf("Error: %s has too many children.\n", parent->name);
return;
}
parent->children[parent->num_children] = child;
parent->num_children++;
if (child->father == NULL) {
child->father = parent;
} else if (child->mother == NULL) {
child->mother = parent;
} else {
printf("Error: %s already has two parents.\n", child->name);
}
}
// 打印一个人及其所有后代
void print_descendants(struct Person *p, int indent) {
for (int i = 0; i < indent; i++) {
printf(" ");
}
printf("%s\n", p->name);
for (int i = 0; i < p->num_children; i++) {
print_descendants(p->children[i], indent + 2);
}
}
int main() {
// 创建家谱
struct Person *p1 = create_person("Grandpa");
struct Person *p2 = create_person("Grandma");
struct Person *p3 = create_person("Dad");
struct Person *p4 = create_person("Mom");
struct Person *p5 = create_person("Me");
struct Person *p6 = create_person("Brother");
struct Person *p7 = create_person("Sister");
add_child(p1, p2);
add_child(p1, p3);
add_child(p2, p4);
add_child(p3, p5);
add_child(p3, p6);
add_child(p3, p7);
// 打印家谱
print_descendants(p1, 0);
return 0;
}
```
输出结果:
```
Grandpa
Grandma
Mom
Dad
Me
Brother
Sister
```
阅读全文