单链表实现员工通讯录管理系统
时间: 2023-09-21 10:08:28 浏览: 101
单链表可以用来实现员工通讯录管理系统。下面是一种可能的实现方式:
定义员工结构体:
```
typedef struct Employee {
int id; // 员工编号
char name[20]; // 员工姓名
char phone[20]; // 员工电话
struct Employee *next; // 指向下一个员工的指针
} Employee;
```
定义链表结构体:
```
typedef struct EmployeeList {
Employee *head; // 链表头指针
int length; // 链表长度
} EmployeeList;
```
初始化链表:
```
EmployeeList initEmployeeList() {
EmployeeList list;
list.head = NULL;
list.length = 0;
return list;
}
```
添加员工:
```
void addEmployee(EmployeeList *list, Employee employee) {
Employee *newEmployee = (Employee*)malloc(sizeof(Employee));
*newEmployee = employee;
newEmployee->next = NULL;
if(list->head == NULL) {
list->head = newEmployee;
} else {
Employee *p = list->head;
while(p->next != NULL) {
p = p->next;
}
p->next = newEmployee;
}
list->length++;
}
```
删除员工:
```
void deleteEmployee(EmployeeList *list, int id) {
if(list->head == NULL) {
return;
}
if(list->head->id == id) {
Employee *temp = list->head;
list->head = list->head->next;
free(temp);
list->length--;
return;
}
Employee *p = list->head;
while(p->next != NULL) {
if(p->next->id == id) {
Employee *temp = p->next;
p->next = p->next->next;
free(temp);
list->length--;
return;
}
p = p->next;
}
}
```
查找员工:
```
Employee* findEmployee(EmployeeList *list, int id) {
Employee *p = list->head;
while(p != NULL) {
if(p->id == id) {
return p;
}
p = p->next;
}
return NULL;
}
```
遍历链表:
```
void traverse(EmployeeList *list) {
Employee *p = list->head;
while(p != NULL) {
printf("id:%d name:%s phone:%s\n", p->id, p->name, p->phone);
p = p->next;
}
}
```
这样,我们就可以使用单链表来实现员工通讯录管理系统了。
阅读全文