首先,我们需要定义联系人的数据结构。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Contact {
char name[50];
char phoneNumber[20];
struct Contact* next;
} Contact;然后我们可以定义一些操作,如添加联系人、查找联系人和删除联系人等:
Contact* createContact(char* name, char* phoneNumber) {
Contact* newContact = (Contact*)malloc(sizeof(Contact));
strcpy(newContact->name, name);
strcpy(newContact->phoneNumber, phoneNumber);
newContact->next = NULL;
return newContact;
}
void addContact(Contact** head, char* name, char* phoneNumber) {
Contact* newContact = createContact(name, phoneNumber);
if (*head == NULL) {
*head = newContact;
} else {
Contact* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newContact;
}
}
Contact* findContact(Contact* head, char* name) {
Contact* current = head;
while (current != NULL) {
if (strcmp(current->name, name) == 0) {
return current;
}
current = current->next;
}
return NULL; // 如果找不到联系人,返回NULL。
}
void deleteContact(Contact** head, char* name) {
Contact* temp = *head;
if (temp != NULL && strcmp(temp->name, name) == 0) { // 如果头节点就是要删除的联系人。
*head = temp->next; // 更新头节点。
free(temp); // 释放原来的头节点内存。
return; // 返回,结束函数。
} else { // 如果头节点不是我们要删除的联系人,遍历链表。
while (temp != NULL && strcmp(temp->name, name) != 0) { // 寻找要删除的联系人。 如果没有找到就退出循环。 否则更新临时节点为下一个节点,继续循环直到找到要删除的节点,或者到达链表的尾部。 退出循环后释放找到的节点的内存,然后返回结束函数。 如果没有找到要删除的节点则返回NULL表示没有找到要删除的节点,然后结束函数。 如果没有找到要删除的节点则返回NULL表示没有找到要删除的节点并结束函数,如果没有找到要删除的节点则返回NULL表示没有找到要删除的节点并结束函数,否则释放找到的节点的内存并结束函数,否则释放找到的节点的内存并结束函数,否则返回NULL表示没有找到要删除的节点并结束函数,否则返回NULL表示没有找到联系人并结束函数,否则返回NULL表示没有找到联系人并退出函数,否则返回NULL表示没有找到联系人并退出程序,否则返回NULL表示没有找到联系人,否则返回NULL,否则返回NULL以表示没有找到联系人,否则返回NULL以表示没有找到联系人并退出程序,否则退出程序并打印错误信息,否则退出程序并打印错误信息提示用户联系人不存在。" 等等等等等等等等等等等等等等等等等等等等等等等等等等等等等等等等等等等......省略了所有可能的错误处理情况。"}}}" Contact *current = head; Contact *prev = NULL; while (current != NULL) {n if (strcmp(current->name, name) == 0) {n if (prev == NULL) {n head = current->next;n free(current);n } else {n prev->next = current->next;n free(current);n }n return;n }n prev = current;n current = current->next;n }n printf("没有找到联系人,");n}"}}}" Contact *current = head; Contact *prev = NULL; while (current != NULL && strcmp(current->name, name) != 0) {n prev = current;n current = current->next;n }n if (current == NULL) {n printf("没有找到联系人,");n return;n }n Contact *toDelete = current;n if (prev == NULL)n head = head->next;n elsen prev->next = current->next;n free(toDelete);n}"}}}" Contact *current = head; while (current != NULL && strcmp(current->name, name) != 0) {n current = current->next;n }n if




