程序功能:建立一个单向链表,头指针是list,链表中每个结点包含姓名、基本工资信息,编写del_list函数删除链表中等于某给定基本工资的所有结点。要求在主函数中先建立单向链表(注:当输入基本工资为0时,表示输入结束。),再输入一个给定基本工资,然后调用del_list函数删除链表中等于给定基本工资的所有结点,最后输出删除后的链表信息。用C语言写
时间: 2023-05-27 18:02:59 浏览: 78
深入浅出linux内核源代码之双向链表list_head(list.h)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Employee {
char name[20];
int salary;
struct Employee *next;
} Employee;
Employee *createList() {
Employee *list = NULL;
Employee *temp = NULL;
int salary;
printf("Input name and salary of employee (enter 0 to finish):\n");
do {
temp = (Employee *)malloc(sizeof(Employee));
scanf("%s %d", temp->name, &salary);
if (salary == 0) {
free(temp);
break;
}
temp->salary = salary;
temp->next = NULL;
if (list == NULL) {
list = temp;
} else {
Employee *p = list;
while (p->next != NULL) {
p = p->next;
}
p->next = temp;
}
} while (1);
return list;
}
void printList(Employee *list) {
Employee *p = list;
while (p != NULL) {
printf("%s %d\n", p->name, p->salary);
p = p->next;
}
}
void del_list(Employee **list, int salary) {
Employee *p = *list;
Employee *prev = NULL;
while (p != NULL) {
if (p->salary == salary) {
if (prev == NULL) {
*list = p->next;
free(p);
p = *list;
} else {
prev->next = p->next;
free(p);
p = prev->next;
}
} else {
prev = p;
p = p->next;
}
}
}
int main() {
Employee *list = createList();
int salary;
printf("Input salary to delete:\n");
scanf("%d", &salary);
del_list(&list, salary);
printf("After delete:\n");
printList(list);
return 0;
}
阅读全文