c语言利用链表通讯录
时间: 2023-11-28 19:06:39 浏览: 93
下面是C语言利用链表实现通讯录的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义通讯录结构体
typedef struct AddressBook {
char name[20];
char phone[20];
struct AddressBook *next;
} AddressBook;
// 添加联系人
void add(AddressBook **head) {
AddressBook *p = (AddressBook *)malloc(sizeof(AddressBook));
printf("请输入姓名:");
scanf("%s", p->name);
printf("请输入电话号码:");
scanf("%s", p->phone);
p->next = *head;
*head = p;
printf("添加成功!\n");
}
// 删除联系人
void del(AddressBook **head) {
char name[20];
printf("请输入要删除的联系人姓名:");
scanf("%s", name);
AddressBook *p = *head;
AddressBook *pre = NULL;
while (p != NULL) {
if (strcmp(p->name, name) == 0) {
if (pre == NULL) {
*head = p->next;
} else {
pre->next = p->next;
}
free(p);
printf("删除成功!\n");
return;
}
pre = p;
p = p->next;
}
printf("未找到该联系人!\n");
}
// 查找联系人
void search(AddressBook *head) {
char name[20];
printf("请输入要查找的联系人姓名:");
scanf("%s", name);
AddressBook *p = head;
while (p != NULL) {
if (strcmp(p->name, name) == 0) {
printf("姓名:%s,电话:%s\n", p->name, p->phone);
return;
}
p = p->next;
}
printf("未找到该联系人!\n");
}
// 显示所有联系人
void show(AddressBook *head) {
AddressBook *p = head;
while (p != NULL) {
printf("姓名:%s,电话:%s\n", p->name, p->phone);
p = p->next;
}
}
int main() {
AddressBook *head = NULL;
int choice;
while (1) {
printf("请选择操作:\n");
printf("1.添加联系人\n");
printf("2.删除联系人\n");
printf("3.查找联系人\n");
printf("4.显示所有联系人\n");
printf("5.退出\n");
scanf("%d", &choice);
switch (choice) {
case 1:
add(&head);
break;
case 2:
del(&head);
break;
case 3:
search(head);
break;
case 4:
show(head);
break;
case 5:
return 0;
default:
printf("输入有误,请重新输入!\n");
break;
}
}
return 0;
}
```
阅读全文