用c语言编写一个程序,建立一个链表结构,每个结点包括职工号,姓名,部门名和工资,采用带头结点尾插法建立链表,职工号为0输入结束,然后输入一部门名,删除链表上所有是该部门职工的结点,输出结果到屏幕上。输入若干行,每一行包括职工号,姓名,部门名和工资,最后一行输入0,再输入删除的部门。例,1 bill HR 5000 2 kate IT 6000 0 HR输出2 kate IT 6000
时间: 2023-08-07 07:08:14 浏览: 99
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Employee{
int id; //职工号
char name[20]; //姓名
char dept[20]; //部门名
int salary; //工资
struct Employee *next; //指向下一个结点的指针
} Employee;
Employee *createList(); //创建链表
void deleteDept(Employee *head, char *dept); //删除指定部门的职工结点
void printList(Employee *head); //打印链表
int main(){
Employee *head = createList();
char dept[20];
printf("请输入要删除的部门名:");
scanf("%s", dept);
deleteDept(head, dept); //删除指定部门的职工结点
printList(head); //打印链表
return 0;
}
Employee *createList(){
Employee *head = (Employee *)malloc(sizeof(Employee)); //创建头结点
head->next = NULL;
Employee *tail = head; //tail指向链表的尾结点
int id, salary;
char name[20], dept[20];
printf("请输入职工号、姓名、部门名和工资:\n");
scanf("%d %s %s %d", &id, name, dept, &salary);
while(id != 0){
Employee *newNode = (Employee *)malloc(sizeof(Employee)); //创建新结点
newNode->id = id;
strcpy(newNode->name, name);
strcpy(newNode->dept, dept);
newNode->salary = salary;
newNode->next = NULL;
tail->next = newNode; //将新结点插入到链表尾部
tail = newNode; //更新尾结点
printf("请输入职工号、姓名、部门名和工资:\n");
scanf("%d %s %s %d", &id, name, dept, &salary);
}
return head;
}
void deleteDept(Employee *head, char *dept){
Employee *p = head->next; //p指向第一个职工结点
Employee *prev = head; //prev指向p的前一个结点
while(p != NULL){
if(strcmp(p->dept, dept) == 0){ //如果p的部门名与删除的部门名相同,则删除该结点
prev->next = p->next;
free(p); //释放p结点的内存空间
p = prev->next; //继续查找下一个职工结点
}
else{ //否则,继续查找下一个职工结点
prev = p;
p = p->next;
}
}
}
void printList(Employee *head){
Employee *p = head->next; //p指向第一个职工结点
while(p != NULL){
printf("%d %s %s %d\n", p->id, p->name, p->dept, p->salary);
p = p->next; //继续打印下一个职工结点
}
}
```
阅读全文