C编程用用链表建立通讯录。通讯录内容有姓名、通讯地址、电话号码。要求: (1) 通讯录是按姓名项的字母顺序排列的; (2) 能查找通讯录中某人的信息。
时间: 2024-12-09 14:18:50 浏览: 119
在C语言中,我们可以使用链表数据结构来建立一个简单的通讯录,因为链表支持动态添加和删除元素,并且可以方便地按照特定条件排序。以下是创建这样一个通讯录的基本步骤:
1. 定义链表节点结构:
```c
typedef struct Node {
char name[50]; // 姓名
char address[100]; // 通讯地址
char phone_number[15]; // 电话号码
struct Node* next; // 指向下一个节点的指针
} Contact;
```
2. 创建链表头结点并初始化为NULL:
```c
Contact* head = NULL;
```
3. 添加联系人(新节点插入到已排序的链表中):
- 如果链表为空,直接将新节点设置为头结点;
- 否则,遍历链表,找到适当的位置插入新节点,保证按姓名排序。
4. 插入函数实现(假设`compareNames`用于比较两个姓名字符串):
```c
void addContact(Contact* list, char* name, char* address, char* phone_number) {
if (!list || strcmp(list->name, name) > 0) { // 如果链表为空或者新名字在旧名字之后
list->next = createNewNode(name, address, phone_number); // 创建新节点并连接
list = list->next;
} else {
addContact(list->next, name, address, phone_number);
}
}
// 辅助函数:创建新节点
Contact* createNewNode(char* name, char* address, char* phone_number) {
Contact* newNode = malloc(sizeof(Contact));
newNode->name = name;
newNode->address = address;
newNode->phone_number = phone_number;
newNode->next = NULL;
return newNode;
}
```
5. 查找功能:
```c
Contact* findContact(Contact* list, char* targetName) {
while (list) {
if (strcmp(list->name, targetName) == 0)
return list;
list = list->next;
}
return NULL; // 如果未找到目标名字,则返回NULL
}
```
6. 显示通讯录内容:
```c
void displayContacts(Contact* list) {
Contact* temp = list;
while (temp) {
printf("%s, %s, %s\n", temp->name, temp->address, temp->phone_number);
temp = temp->next;
}
}
```
阅读全文
相关推荐
















