数据结构C语言单链表通讯录实现增删改查的代码
时间: 2024-10-12 16:16:26 浏览: 55
在C语言中,我们可以使用单链表数据结构来实现一个简单的通讯录功能,包括增加联系人、删除联系人、修改联系信息以及查询联系人等操作。下面是一个基础的示例,这里假设每个节点包含姓名和电话号码两个属性:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
char name[50];
char phone[20];
struct Node* next;
} Contact;
// 创建新节点
Contact* createNode(char* name, char* phone) {
Contact* newNode = (Contact*)malloc(sizeof(Contact));
if (newNode != NULL) {
strcpy(newNode->name, name);
strcpy(newNode->phone, phone);
newNode->next = NULL;
}
return newNode;
}
// 在链表末尾添加节点
void addContact(Contact** head, char* name, char* phone) {
Contact* newNode = createNode(name, phone);
if (*head == NULL) {
*head = newNode;
} else {
Contact* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// 删除联系人(根据名字)
void deleteContact(Contact** head, char* name) {
if (*head == NULL) return;
if ((*head)->name == name) {
Contact* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Contact* prev = *head;
Contact* curr = *head->next;
while (curr != NULL && strcmp(curr->name, name) != 0) {
prev = curr;
curr = curr->next;
}
if (curr != NULL) {
prev->next = curr->next;
free(curr);
}
}
// 修改联系信息(根据名字)
void modifyContact(Contact** head, char* oldName, char* newName, char* newPhone) {
Contact* temp = *head;
while (temp != NULL) {
if (strcmp(temp->name, oldName) == 0) {
strcpy(temp->name, newName);
strcpy(temp->phone, newPhone);
break;
}
temp = temp->next;
}
}
// 查询联系人
void searchContact(Contact* head, char* name) {
Contact* temp = head;
while (temp != NULL) {
if (strcmp(temp->name, name) == 0) {
printf("Name: %s, Phone: %s\n", temp->name, temp->phone);
break;
}
temp = temp->next;
}
if (temp == NULL) {
printf("Contact not found.\n");
}
}
int main() {
// 初始化链表为空
Contact* head = NULL;
// 添加示例联系人
addContact(&head, "Alice", "123456789");
addContact(&head, "Bob", "987654321");
// 执行其他操作
// ...
return 0;
}
```
阅读全文
相关推荐


















