在c语言中用单链表实现通讯录系统,具有输入,查找,添加,删除,修改和输出功能
时间: 2024-10-24 21:16:21 浏览: 14
在C语言中,我们可以使用结构体和指针来构建一个简单的单链表通讯录系统。首先,我们需要定义一个包含姓名和联系方式的节点结构:
```c
typedef struct Contact {
char name[50];
char phone[20];
struct Contact* next;
} Contact;
```
接下来,我们创建一些基本操作的函数:
1. **输入**:允许用户输入新联系人信息
```c
void addContact(Contact** head, char* name, char* phone) {
Contact* newNode = (Contact*)malloc(sizeof(Contact));
strcpy(newNode->name, name);
strcpy(newNode->phone, phone);
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
Contact* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
```
2. **查找**:按名字查找特定联系人
```c
Contact* searchByName(Contact* head, char* name) {
Contact* current = head;
while (current != NULL && strcmp(current->name, name) != 0) {
current = current->next;
}
return current;
}
```
3. **删除**:按名字删除联系人
```c
void deleteContact(Contact** head, char* name) {
if (*head == NULL || (*head)->name == NULL) return;
Contact* temp = *head;
Contact* prev = NULL;
if(strcmp(temp->name, name) == 0){
*head = temp->next;
free(temp);
return;
}
while(temp != NULL && strcmp(temp->name, name) != 0){
prev = temp;
temp = temp->next;
}
if(temp != NULL){
prev->next = temp->next;
free(temp);
}
}
```
4. **修改**:更新联系人的信息
```c
void updateContact(Contact** head, char* oldName, char* newName, char* newPhone) {
Contact* contact = searchByName(head, oldName);
if (contact != NULL) {
strcpy(contact->name, newName);
strcpy(contact->phone, newPhone);
}
}
```
5. **输出**:遍历链表显示所有联系人
```c
void displayContacts(Contact* head) {
if (head == NULL) {
printf("通讯录为空\n");
} else {
Contact* current = head;
while (current != NULL) {
printf("姓名:%s,电话:%s\n", current->name, current->phone);
current = current->next;
}
}
}
```
阅读全文