用c语言单链表写一个通讯录系统
时间: 2023-11-25 21:06:54 浏览: 54
好的,下面是一个简单的通讯录系统的单链表实现,使用C语言编写:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* 定义通讯录结构体 */
typedef struct contact {
char name[20];
char phone[20];
struct contact *next;
} Contact;
/* 创建通讯录 */
Contact *create_contact() {
Contact *head, *tail, *pnew;
head = tail = (Contact*)malloc(sizeof(Contact));
printf("请输入姓名:");
scanf("%s", tail->name);
printf("请输入电话:");
scanf("%s", tail->phone);
while (strcmp(tail->name, "0") != 0) {
pnew = (Contact*)malloc(sizeof(Contact));
printf("请输入姓名:");
scanf("%s", pnew->name);
if (strcmp(pnew->name, "0") == 0) {
break;
}
printf("请输入电话:");
scanf("%s", pnew->phone);
tail->next = pnew;
tail = pnew;
}
tail->next = NULL;
return head;
}
/* 显示通讯录 */
void show_contact(Contact *head) {
Contact *p = head;
printf("姓名\t\t电话\n");
while (p != NULL) {
printf("%s\t\t%s\n", p->name, p->phone);
p = p->next;
}
}
/* 查找联系人 */
Contact *find_contact(Contact *head, char *name) {
Contact *p = head;
while (p != NULL) {
if (strcmp(p->name, name) == 0) {
return p;
}
p = p->next;
}
return NULL;
}
/* 添加联系人 */
Contact *add_contact(Contact *head, char *name, char *phone) {
Contact *pnew = (Contact*)malloc(sizeof(Contact));
strcpy(pnew->name, name);
strcpy(pnew->phone, phone);
pnew->next = head;
head = pnew;
return head;
}
/* 删除联系人 */
Contact *delete_contact(Contact *head, char *name) {
Contact *p = head, *pre = NULL;
while (p != NULL) {
if (strcmp(p->name, name) == 0) {
if (pre == NULL) {
head = p->next;
} else {
pre->next = p->next;
}
free(p);
return head;
}
pre = p;
p = p->next;
}
return head;
}
/* 修改联系人 */
void modify_contact(Contact *head, char *name, char *phone) {
Contact *p = find_contact(head, name);
if (p != NULL) {
strcpy(p->phone, phone);
}
}
int main() {
Contact *head, *p;
char name[20], phone[20];
int choice;
head = create_contact();
do {
printf("========================\n");
printf("1. 显示所有联系人\n");
printf("2. 查找联系人\n");
printf("3. 添加联系人\n");
printf("4. 删除联系人\n");
printf("5. 修改联系人\n");
printf("0. 退出\n");
printf("========================\n");
printf("请输入选项:");
scanf("%d", &choice);
switch (choice) {
case 1:
show_contact(head);
break;
case 2:
printf("请输入姓名:");
scanf("%s", name);
p = find_contact(head, name);
if (p != NULL) {
printf("姓名\t\t电话\n");
printf("%s\t\t%s\n", p->name, p->phone);
} else {
printf("未找到该联系人\n");
}
break;
case 3:
printf("请输入姓名:");
scanf("%s", name);
printf("请输入电话:");
scanf("%s", phone);
head = add_contact(head, name, phone);
printf("添加成功!\n");
break;
case 4:
printf("请输入姓名:");
scanf("%s", name);
head = delete_contact(head, name);
printf("删除成功!\n");
break;
case 5:
printf("请输入姓名:");
scanf("%s", name);
printf("请输入电话:");
scanf("%s", phone);
modify_contact(head, name, phone);
printf("修改成功!\n");
break;
case 0:
break;
default:
printf("输入有误,请重新输入!\n");
break;
}
} while (choice != 0);
return 0;
}
```
在这个例子中,我们使用单链表来实现一个简单的通讯录系统,包括创建通讯录、显示通讯录、查找联系人、添加联系人、删除联系人、修改联系人等功能。通过这个例子,您可以了解单链表在实际应用中的使用方法,并掌握基本的链表操作技巧。