数据结构用代码建员工表,包括工号姓名月薪,输入工号可查询员工查询全部信息
时间: 2024-03-16 13:44:51 浏览: 19
好的,以下是一个示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 50
#define MAX_ID_LEN 10
typedef struct Employee {
char name[MAX_NAME_LEN];
char id[MAX_ID_LEN];
float salary;
struct Employee *next;
} Employee;
Employee *head = NULL;
void addEmployee(char name[], char id[], float salary) {
Employee *newEmployee = (Employee*) malloc(sizeof(Employee));
strcpy(newEmployee->name, name);
strcpy(newEmployee->id, id);
newEmployee->salary = salary;
newEmployee->next = head;
head = newEmployee;
}
void printEmployee(Employee *employee) {
printf("Name: %s\n", employee->name);
printf("ID: %s\n", employee->id);
printf("Salary: %.2f\n", employee->salary);
}
Employee* findEmployee(char id[]) {
Employee *current = head;
while (current != NULL) {
if (strcmp(current->id, id) == 0) {
return current;
}
current = current->next;
}
return NULL;
}
void printAllEmployees() {
Employee *current = head;
while (current != NULL) {
printEmployee(current);
current = current->next;
}
}
int main() {
addEmployee("John Smith", "123456", 5000.0);
addEmployee("Mary Johnson", "789012", 4000.0);
addEmployee("David Lee", "345678", 6000.0);
char searchId[MAX_ID_LEN];
printf("Please enter an employee ID to search: ");
scanf("%s", searchId);
Employee *result = findEmployee(searchId);
if (result != NULL) {
printEmployee(result);
} else {
printf("Employee not found.\n");
}
return 0;
}
```
在这个代码中,我们使用了链表来存储员工信息,每个员工信息包括姓名、ID、月薪等属性。通过 addEmployee 函数,我们可以将新员工添加到链表的头部。通过 findEmployee 函数,我们可以根据输入的工号在链表中查找相应的员工。通过 printAllEmployees 函数,我们可以打印出所有员工的信息。在主函数中,我们通过 scanf 函数获取用户输入的工号,然后调用 findEmployee 函数查找员工信息并打印。