
请注意,这是一个基本的示例,并没有包含错误处理和用户输入验证等复杂功能。在实际应用中,你可能需要增加这些功能来提高程序的健壮性。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义联系人结构体
typedef struct Contact {
char name[50];
char phoneNumber[20];
struct Contact* next;
} Contact;
// 添加新的联系人
void addContact(Contact** head_ref, char name[], char number[]) {
Contact* newContact = (Contact*)malloc(sizeof(Contact)); // 创建新的联系人节点
strcpy(newContact->name, name); // 复制名字到节点
strcpy(newContact->phoneNumber, number); // 复制电话号码到节点
newContact->next = *head_ref; // 将新节点放在链表头部
*head_ref = newContact; // 更新头指针指向新节点
}
// 查找联系人
Contact* findContact(Contact* head, char name[]) {
Contact* temp = head; // 开始从头部遍历链表
while (temp != NULL) { // 当链表未结束时继续遍历
if (strcmp(temp->name, name) == 0) { // 如果找到匹配的名字,返回该节点的指针
return temp;
}
temp = temp->next; // 否则继续遍历链表
}
return NULL; // 如果未找到匹配的联系人,返回NULL
}
// 显示所有联系人列表
void displayContacts(Contact* head) {
Contact* temp = head; // 从头部开始遍历链表
while (temp != NULL) { // 当链表未结束时继续遍历
printf("Name: %snPhone Number: %sn", temp->name, temp->phoneNumber);
temp = temp->next; // 移动到下一个节点
}
}
int main() {
Contact* head = NULL; // 初始化链表为空
char choice; // 用户的选择(用于控制菜单)
char name[50], number[20]; // 用于存储联系人的名字和电话号码的变量
while (1) { // 主循环,用于反复询问用户输入并处理请求,直到用户选择退出程序为止。
printf("n1. Add Contactn"); // 添加联系人的选项菜单项,用户输入相应的数字来选择相应的操作,这里假设用户已经知道如何操作,具体实现可以根据实际需求进行修改,例如添加更多的菜单项或者更详细的提示信息,这里假设用户输入的数字是合法的(即存在于菜单项中),如果输入的数字不合法,程序可能会进入无限循环或者出现未定义的行为,因此在实际应用中需要添加相应的错误处理机制来保证程序的健壮性。"); printf("n2. Find Contactn"); printf("n3. Display Contactsn"); printf("n4. Exitn"); printf("Enter your choice: "); scanf("%c", &choice); switch (choice) { case ’1’: printf("Enter name and phone number of contact to add: "); scanf("%s %s", name, number); addContact(&head, name, number); break; case ’2’: printf("Enter name of contact to find: "); scanf("%s", name); if (findContact(head, name)) { printf("Found contact with name %s and phone number %sn", name, number); } else { printf("Sorry, contact not found.n"); } break; case ’3’: displayContacts(head); break; case ’4’: exit(0); default: printf("Invalid choice. Please enter a valid choice.n"); break; } } return 0; }```




