写一个单向链表存放员工name,age,gender,要求增删改查的代码
时间: 2023-04-01 11:04:01 浏览: 94
好的,以下是单向链表存放员工信息的代码:
// 定义员工结构体
typedef struct Employee {
char name[20];
int age;
char gender;
struct Employee *next;
} Employee;
// 初始化链表
Employee *initList() {
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;
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;
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: %c\n", p->name, p->age, p->gender);
return;
}
p = p->next;
}
printf("Employee not found.\n");
}
// 测试代码
int main() {
Employee *head = initList();
addEmployee(head, "Tom", 25, 'M');
addEmployee(head, "Lucy", 23, 'F');
addEmployee(head, "Jack", 30, 'M');
printf("Before delete:\n");
findEmployee(head, "Lucy");
deleteEmployee(head, "Lucy");
printf("After delete:\n");
findEmployee(head, "Lucy");
printf("Before modify:\n");
findEmployee(head, "Tom");
modifyEmployee(head, "Tom", 26, 'M');
printf("After modify:\n");
findEmployee(head, "Tom");
return ;
}
阅读全文