好的,下面是一个简单的基于二叉排序树的通讯录管理系统的 C 语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义通讯录节点
typedef struct contact_node {
char name[20];
char phone[15];
struct contact_node *left;
struct contact_node *right;
} ContactNode;
// 初始化通讯录根节点
ContactNode *init_contact() {
ContactNode *root = (ContactNode *)malloc(sizeof(ContactNode));
strcpy(root->name, "");
strcpy(root->phone, "");
root->left = NULL;
root->right = NULL;
return root;
}
// 插入通讯录节点
ContactNode *insert_contact(ContactNode *root, char *name, char *phone) {
if (root == NULL) {
ContactNode *new_node = (ContactNode *)malloc(sizeof(ContactNode));
strcpy(new_node->name, name);
strcpy(new_node->phone, phone);
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
if (strcmp(name, root->name) < 0) {
root->left = insert_contact(root->left, name, phone);
} else if (strcmp(name, root->name) > 0) {
root->right = insert_contact(root->right, name, phone);
}
return root;
}
// 查找通讯录节点
ContactNode *find_contact(ContactNode *root, char *name) {
if (root == NULL) {
return NULL;
}
if (strcmp(name, root->name) == 0) {
return root;
} else if (strcmp(name, root->name) < 0) {
return find_contact(root->left, name);
} else {
return find_contact(root->right, name);
}
}
// 遍历通讯录
void traverse_contact(ContactNode *root) {
if (root == NULL) {
return;
}
traverse_contact(root->left);
printf("Name: %s, Phone: %s\n", root->name, root->phone);
traverse_contact(root->right);
}
// 释放通讯录内存
void free_contact(ContactNode *root) {
if (root == NULL) {
return;
}
free_contact(root->left);
free_contact(root->right);
free(root);
}
int main() {
ContactNode *root = init_contact();
char name[20], phone[15];
int choice = 0;
while (1) {
printf("\n1. Add a contact\n");
printf("2. Find a contact\n");
printf("3. Traverse all contacts\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter name: ");
scanf("%s", name);
printf("Enter phone: ");
scanf("%s", phone);
root = insert_contact(root, name, phone);
printf("Contact added successfully!\n");
break;
case 2:
printf("Enter name to search: ");
scanf("%s", name);
ContactNode *node = find_contact(root, name);
if (node != NULL) {
printf("Name: %s, Phone: %s\n", node->name, node->phone);
} else {
printf("Contact not found!\n");
}
break;
case 3:
traverse_contact(root);
break;
case 4:
free_contact(root);
printf("Exiting...\n");
exit(0);
default:
printf("Invalid choice!\n");
break;
}
}
return 0;
}
```
这个通讯录管理系统基于二叉排序树实现,用户可以通过添加、查找和遍历通讯录来管理联系人。每个通讯录节点包含一个姓名和一个电话号码。在添加联系人时,程序将按照姓名的字典序插入到二叉排序树中。在查找联系人时,程序将按照二叉排序树的规则查找节点。在遍历通讯录时,程序将按照中序遍历的顺序输出所有节点的姓名和电话号码。