以通讯录为应用对象,用c++设计一个链表处理系统。
时间: 2023-06-07 21:10:55 浏览: 66
好的,我理解了你的问题。以下是基于通讯录的链表处理系统的 C 代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义联系人结构体
struct Contact {
char name[50];
char phone[20];
char email[50];
struct Contact *next;
};
// 插入新的联系人
struct Contact *addContact(struct Contact *list) {
struct Contact *newContact = malloc(sizeof(struct Contact));
if (newContact == NULL) {
printf("Error: Out of memory\n");
exit(1);
}
printf("Please enter the contact's name: ");
scanf("%s", newContact->name);
printf("Please enter the contact's phone: ");
scanf("%s", newContact->phone);
printf("Please enter the contact's email: ");
scanf("%s", newContact->email);
newContact->next = list;
return newContact;
}
// 查找联系人
struct Contact *findContact(struct Contact *list, const char *name) {
struct Contact *temp = list;
while (temp != NULL) {
if (strcmp(temp->name, name) == 0) {
return temp;
}
temp = temp->next;
}
return NULL;
}
// 删除指定联系人
struct Contact *deleteContact(struct Contact *list, const char *name) {
struct Contact *temp = list, *prev = NULL;
while (temp != NULL) {
if (strcmp(temp->name, name) == 0) {
if (prev == NULL) {
list = temp->next;
} else {
prev->next = temp->next;
}
free(temp);
return list;
}
prev = temp;
temp = temp->next;
}
printf("Error: Contact not found\n");
return list;
}
// 打印所有联系人
void printContacts(struct Contact *list) {
struct Contact *temp = list;
printf("Name\tPhone\t\tEmail\n");
while (temp != NULL) {
printf("%s\t%s\t%s\n", temp->name, temp->phone, temp->email);
temp = temp->next;
}
}
// 主函数
int main() {
struct Contact *head = NULL;
int choice;
char name[50];
do {
printf("\nContacts List\n");
printf("-------------\n");
printf("1. Add contact\n");
printf("2. Find contact\n");
printf("3. Delete contact\n");
printf("4. Print all contacts\n");
printf("5. Exit\n");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
head = addContact(head);
break;
case 2:
printf("Please enter the name to search: ");
scanf("%s", name);
struct Contact *found = findContact(head, name);
if (found == NULL) {
printf("Contact not found\n");
} else {
printf("Name: %s\nPhone: %s\nEmail: %s\n",
found->name, found->phone, found->email);
}
break;
case 3:
printf("Please enter the name to delete: ");
scanf("%s", name);
head = deleteContact(head, name);
break;
case 4:
printContacts(head);
break;
case 5:
printf("Goodbye!\n");
break;
default:
printf("Invalid choice\n");
break;
}
} while (choice != 5);
return 0;
}
```
这个程序使用链表数据结构来存储联系人信息,每个联系人都包含姓名、电话和电子邮件地址。程序提供了四个操作:添加联系人、查找联系人、删除联系人和打印所有联系人。当您运行程序时,菜单会提示您输入选项,然后根据您的选择执行相应的操作。