用链表实现通讯录管理
时间: 2024-01-07 13:04:14 浏览: 29
以下是使用链表实现通讯录管理的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义联系人结构体
typedef struct contact {
int id; // 编号
char name[20]; // 姓名
char gender[5]; // 性别
char phone[12]; // 电话
struct contact *next; // 指向下一个联系人的指针
} Contact;
// 初始化链表
Contact *init() {
Contact *head = (Contact*)malloc(sizeof(Contact));
head->next = NULL;
return head;
}
// 添加联系人
void add(Contact *head, int id, char *name, char *gender, char *phone) {
Contact *p = head;
while (p->next != NULL) {
p = p->next;
}
Contact *new_contact = (Contact*)malloc(sizeof(Contact));
new_contact->id = id;
strcpy(new_contact->name, name);
strcpy(new_contact->gender, gender);
strcpy(new_contact->phone, phone);
new_contact->next = NULL;
p->next = new_contact;
}
// 删除联系人
void del(Contact *head, char *name) {
Contact *p = head->next;
Contact *pre = head;
while (p != NULL) {
if (strcmp(p->name, name) == 0) {
pre->next = p->next;
free(p);
return;
}
pre = p;
p = p->next;
}
printf("联系人不存在\n");
}
// 修改联系人
void update(Contact *head, char *name, char *gender, char *phone) {
Contact *p = head->next;
while (p != NULL) {
if (strcmp(p->name, name) == 0) {
strcpy(p->gender, gender);
strcpy(p->phone, phone);
return;
}
p = p->next;
}
printf("联系人不存在\n");
}
// 查找联系人
void search(Contact *head, char *name) {
Contact *p = head->next;
while (p != NULL) {
if (strcmp(p->name, name) == 0) {
printf("编号:%d\t姓名:%s\t性别:%s\t电话:%s\n", p->id, p->name, p->gender, p->phone);
return;
}
p = p->next;
}
printf("联系人不存在\n");
}
// 显示所有联系人
void show(Contact *head) {
Contact *p = head->next;
while (p != NULL) {
printf("编号:%d\t姓名:%s\t性别:%s\t电话:%s\n", p->id, p->name, p->gender, p->phone);
p = p->next;
}
}
// 释放链表内存
void free_list(Contact *head) {
Contact *p = head;
while (p != NULL) {
Contact *temp = p;
p = p->next;
free(temp);
}
}
int main() {
Contact *head = init();
add(head, 1, "张三", "男", "12345678901");
add(head, 2, "李四", "女", "23456789012");
add(head, 3, "王五", "男", "34567890123");
show(head);
printf("---------------\n");
del(head, "李四");
show(head);
printf("---------------\n");
update(head, "张三", "女", "11111111111");
search(head, "张三");
printf("---------------\n");
show(head);
free_list(head);
return 0;
}
```