写一个单向链表存放员工name,age,gender,要求增删改查源码
时间: 2023-04-03 20:01:18 浏览: 98
以下是单向链表存放员工name,age,gender的增删改查源码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义员工结构体
typedef struct Employee {
char name[20];
int age;
char gender[10];
struct Employee *next;
} Employee;
// 创建员工链表
Employee *createEmployeeList() {
Employee *head = (Employee *)malloc(sizeof(Employee));
head->next = NULL;
return head;
}
// 添加员工
void addEmployee(Employee *head, char *name, int age, char *gender) {
Employee *newEmployee = (Employee *)malloc(sizeof(Employee));
strcpy(newEmployee->name, name);
newEmployee->age = age;
strcpy(newEmployee->gender, gender);
newEmployee->next = NULL;
Employee *p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = newEmployee;
}
// 删除员工
void deleteEmployee(Employee *head, char *name) {
Employee *p = head->next;
Employee *pre = head;
while (p != NULL) {
if (strcmp(p->name, name) == ) {
pre->next = p->next;
free(p);
return;
}
pre = p;
p = p->next;
}
}
// 修改员工信息
void modifyEmployee(Employee *head, char *name, int age, char *gender) {
Employee *p = head->next;
while (p != NULL) {
if (strcmp(p->name, name) == ) {
p->age = age;
strcpy(p->gender, gender);
return;
}
p = p->next;
}
}
// 查找员工
void findEmployee(Employee *head, char *name) {
Employee *p = head->next;
while (p != NULL) {
if (strcmp(p->name, name) == ) {
printf("Name: %s, Age: %d, Gender: %s\n", p->name, p->age, p->gender);
return;
}
p = p->next;
}
printf("Employee not found.\n");
}
// 打印员工链表
void printEmployeeList(Employee *head) {
Employee *p = head->next;
while (p != NULL) {
printf("Name: %s, Age: %d, Gender: %s\n", p->name, p->age, p->gender);
p = p->next;
}
}
int main() {
Employee *head = createEmployeeList();
addEmployee(head, "Tom", 25, "Male");
addEmployee(head, "Lucy", 30, "Female");
addEmployee(head, "John", 28, "Male");
printf("Employee List:\n");
printEmployeeList(head);
printf("\nDelete employee Lucy:\n");
deleteEmployee(head, "Lucy");
printEmployeeList(head);
printf("\nModify employee John's information:\n");
modifyEmployee(head, "John", 29, "Male");
printEmployeeList(head);
printf("\nFind employee Tom:\n");
findEmployee(head, "Tom");
return ;
}
阅读全文