程序功能:建立一个单向链表,头指针是list,链表中每个结点包含姓名、基本工资信息,编写del_list函数删除链表中等于某给定基本工资的所有结点。要求在主函数中先建立单向链表(注:当输入基本工资为0时,表示输入结束。),再输入一个给定基本工资,然后调用del_list函数删除链表中等于给定基本工资的所有结点,最后输出删除后的链表信息。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct person {
char name[20];
double wage;
struct person* next;
};
struct person* add_person(struct person* pNew, struct person* head) //增加
{
struct person* p;
if (head == NULL)
{
head = pNew;
}
else
{
for (p = head; p->next != NULL; p = p->next);
p->next = pNew;
}
return head;
}
struct person* del_list(struct person* head) //删除指定工资的员工
{
double t;
printf("输入要删除的员工的工资:");
scanf("%lf", &t);
struct person* p;
struct person* pLast = NULL;
int ct = 0;
if (head == NULL)
{
printf("删除失败,无职工信息\n");
}
else
{
for (p = head; p != NULL;) //遍历
{
if (p->wage == t) //匹配
{
if (p == head) //删除位置为头结点
{
p = p->next;
free(head);
head = p;
}
else //删除位置为中间节点
{
p = p->next;
free(pLast->next);
pLast->next = p;
}
}
else //不匹配
{
pLast = p;
p = p->next;
}
}
}
return head;
}
void show_list(struct person* head) //输出所有信息
{
struct person* p;
if (head == NULL)
{
printf("无职工信息\n");
}
else
{
printf(" 姓名 工资\n");
for (p = head; p != NULL; p = p->next)
{
printf(" %-14s %.2lf\n", p->name, p->wage);
}
}
}
int main()
{
struct person* head = NULL;
char n[20];
double m;
while (1)
{
struct person* p = (struct person*)malloc(sizeof(struct person));
printf("\n请输入工资(输入0结束):");
scanf("%lf", &m);
if (m == 0)
{
free(p);
break;
}
printf("请输入姓名:");
scanf("%s", n);
if (p == NULL)
break;
strcpy(p->name, n);
p->wage = m;
p->next = NULL;
head = add_person(p, head);
}
head = del_list(head);
show_list(head);
return 0;
}