用树形结构写家谱管理系统的c语言代码
时间: 2023-09-27 10:06:59 浏览: 119
好的,下面是一个用树形结构实现家谱管理系统的C语言代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 20 // 最大姓名长度
// 定义家庭成员结构体
typedef struct family_member {
char name[MAX_NAME_LEN]; // 成员姓名
struct family_member *father; // 父亲指针
struct family_member *mother; // 母亲指针
struct family_member *next_sibling; // 兄弟姐妹指针
} FamilyMember;
// 创建家庭成员函数
FamilyMember *createFamilyMember(char *name) {
// 分配内存空间
FamilyMember *member = (FamilyMember *)malloc(sizeof(FamilyMember));
if (member == NULL) {
printf("Error: memory allocation failed!\n");
return NULL;
}
// 初始化成员信息
strcpy(member->name, name);
member->father = NULL;
member->mother = NULL;
member->next_sibling = NULL;
return member;
}
// 添加父亲函数
void addFather(FamilyMember *member, char *name) {
if (member == NULL) {
printf("Error: the member is NULL!\n");
return;
}
if (member->father != NULL) {
printf("Error: the member already has a father!\n");
return;
}
member->father = createFamilyMember(name);
}
// 添加母亲函数
void addMother(FamilyMember *member, char *name) {
if (member == NULL) {
printf("Error: the member is NULL!\n");
return;
}
if (member->mother != NULL) {
printf("Error: the member already has a mother!\n");
return;
}
member->mother = createFamilyMember(name);
}
// 添加兄弟姐妹函数
void addSibling(FamilyMember *member, char *name) {
if (member == NULL) {
printf("Error: the member is NULL!\n");
return;
}
if (member->father == NULL && member->mother == NULL) {
printf("Error: the member doesn't have parents!\n");
return;
}
FamilyMember *sibling = createFamilyMember(name);
if (member->father != NULL) {
// 添加到父亲的子节点中
if (member->father->next_sibling == NULL) {
member->father->next_sibling = sibling;
} else {
FamilyMember *p = member->father->next_sibling;
while (p->next_sibling != NULL) {
p = p->next_sibling;
}
p->next_sibling = sibling;
}
} else {
// 添加到母亲的子节点中
if (member->mother->next_sibling == NULL) {
member->mother->next_sibling = sibling;
} else {
FamilyMember *p = member->mother->next_sibling;
while (p->next_sibling != NULL) {
p = p->next_sibling;
}
p->next_sibling = sibling;
}
}
}
// 遍历家谱
void traverseFamilyTree(FamilyMember *root) {
if (root == NULL) {
return;
}
printf("%s\n", root->name);
if (root->father != NULL) {
traverseFamilyTree(root->father);
}
if (root->mother != NULL) {
traverseFamilyTree(root->mother);
}
if (root->next_sibling != NULL) {
traverseFamilyTree(root->next_sibling);
}
}
int main() {
// 创建家谱树
FamilyMember *root = createFamilyMember("张三");
addFather(root, "张父");
addMother(root, "张母");
addSibling(root, "张四");
addSibling(root, "张五");
// 遍历家谱树
traverseFamilyTree(root);
return 0;
}
```
以上代码实现了家谱管理系统的基本功能,通过树形结构来表示家庭成员之间的关系。你可以根据需要进行修改或完善。
阅读全文