写一个单向链表存放员工name,age,gender,要求增删改查
时间: 2023-04-03 12:01:32 浏览: 69
好的,我可以回答这个问题。为了存储员工的姓名、年龄和性别,我们可以定义一个结构体,如下所示:
```
typedef struct Employee {
char name[20];
int age;
char gender;
struct Employee *next;
} Employee;
```
这个结构体包含了员工的姓名、年龄和性别,以及一个指向下一个员工的指针。接下来,我们可以定义一个指向链表头部的指针,如下所示:
```
Employee *head = NULL;
```
这个指针初始化为 NULL,表示链表为空。接下来,我们可以实现增删改查的操作。
1. 增加员工
要增加一个员工,我们需要先创建一个新的 Employee 结构体,然后将其插入到链表的头部。代码如下所示:
```
Employee *new_employee = (Employee *)malloc(sizeof(Employee));
strcpy(new_employee->name, "张三");
new_employee->age = 25;
new_employee->gender = 'M';
new_employee->next = head;
head = new_employee;
```
这个代码片段创建了一个新的员工,将其插入到链表的头部。
2. 删除员工
要删除一个员工,我们需要先找到该员工的前一个节点,然后将其指针指向下一个节点。代码如下所示:
```
Employee *prev_employee = NULL;
Employee *current_employee = head;
while (current_employee != NULL && strcmp(current_employee->name, "张三") != ) {
prev_employee = current_employee;
current_employee = current_employee->next;
}
if (current_employee != NULL) {
if (prev_employee == NULL) {
head = current_employee->next;
} else {
prev_employee->next = current_employee->next;
}
free(current_employee);
}
```
这个代码片段查找名为 "张三" 的员工,并将其从链表中删除。
3. 修改员工
要修改一个员工的信息,我们需要先找到该员工的节点,然后修改其属性。代码如下所示:
```
Employee *current_employee = head;
while (current_employee != NULL && strcmp(current_employee->name, "张三") != ) {
current_employee = current_employee->next;
}
if (current_employee != NULL) {
current_employee->age = 30;
current_employee->gender = 'F';
}
```
这个代码片段查找名为 "张三" 的员工,并将其年龄修改为 30,性别修改为女性。
4. 查找员工
要查找一个员工,我们需要遍历整个链表,直到找到该员工。代码如下所示:
```
Employee *current_employee = head;
while (current_employee != NULL && strcmp(current_employee->name, "张三") != ) {
current_employee = current_employee->next;
}
if (current_employee != NULL) {
printf("姓名:%s,年龄:%d,性别:%c\n", current_employee->name, current_employee->age, current_employee->gender);
} else {
printf("未找到该员工\n");
}
```
这个代码片段查找名为 "张三" 的员工,并输出其姓名、年龄和性别。如果未找到该员工,则输出提示信息。
希望这个回答能够帮助到你!
阅读全文