在C语言中,如何设计并实现一个基于单链表的员工通讯录管理系统?请详细说明如何添加员工信息、查询、修改和删除通讯录数据。
时间: 2024-12-07 07:31:07 浏览: 32
为了实现一个基于单链表的员工通讯录管理系统,你需要深入理解单链表的特性以及在C语言中的操作方法。首先,定义链表节点的数据结构,通常包括员工的基本信息和指向下一节点的指针。然后,实现链表的基本操作函数,如创建链表、添加节点、删除节点、查找节点、修改节点信息以及遍历链表等。以下是具体操作的示例代码:
参考资源链接:[单位员工通讯录管理系统 - 数据结构线性表应用](https://wenku.csdn.net/doc/7dhotf8fuo?spm=1055.2569.3001.10343)
首先,定义员工信息的结构体和链表节点结构体:
```c
typedef struct Employee {
int id;
char name[50];
char phone_number[15];
char office_phone[15];
struct Employee *next; // 指向下一个节点的指针
} EmployeeNode, *EmployeeLinkedList;
```
创建链表(初始化为NULL):
```c
EmployeeLinkedList createList() {
EmployeeLinkedList head = NULL;
return head;
}
```
插入节点到链表末尾:
```c
void insertNode(EmployeeLinkedList *head, EmployeeNode new_node) {
if (*head == NULL) {
*head = new_node;
} else {
EmployeeNode current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = new_node;
}
}
```
删除指定节点:
```c
void deleteNode(EmployeeLinkedList *head, int id) {
EmployeeNode current = *head;
EmployeeNode previous = NULL;
if (current != NULL && current->id == id) {
*head = current->next;
free(current);
return;
}
while (current != NULL && current->id != id) {
previous = current;
current = current->next;
}
if (current == NULL) {
return; // 没有找到
}
previous->next = current->next;
free(current);
}
```
查找节点(根据id):
```c
EmployeeNode *findNode(EmployeeLinkedList head, int id) {
EmployeeNode current = head;
while (current != NULL) {
if (current->id == id) {
return current;
}
current = current->next;
}
return NULL; // 没有找到
}
```
修改节点信息:
```c
void updateNode(EmployeeNode *node, const char *new_name, const char *new_phone, const char *new_office_phone) {
if (node != NULL) {
strcpy(node->name, new_name);
strcpy(node->phone_number, new_phone);
strcpy(node->office_phone, new_office_phone);
}
}
```
遍历链表并打印所有员工信息:
```c
void traverseList(EmployeeLinkedList head) {
EmployeeNode *current = head;
while (current != NULL) {
printf(
参考资源链接:[单位员工通讯录管理系统 - 数据结构线性表应用](https://wenku.csdn.net/doc/7dhotf8fuo?spm=1055.2569.3001.10343)
阅读全文