C语言链表员工记录程序修改求助:改为按员工编号搜索
链表员工记录搜索功能修复方案
针对需求:将搜索改为按员工编号、解决找到匹配后仍提示未找到的问题,以下是修改后的完整代码及关键说明:
修改后完整代码
#include<stdio.h> #include<stdlib.h> #include<string.h> struct node* createnode(struct node*); void display(struct node*); void search(struct node*); struct node { int emp_num; char name[10]; int Year_service; float salary; struct node* ptr; }; int main() { struct node* head; int b,i; head=NULL; while(1) { printf("\n1-> to enter the employee details\n2->to display All employee details\n3->to search an element\nEnter the value\n"); scanf("%d",&b); switch(b) { case 1: printf("\nEnter the Number of Employee's Detail you would like to enter\n"); scanf("%d",&i); while(i>0) { head=createnode(head); i--; } break; case 2: display(head); break; case 3: search(head); break; default : printf("\nEnter Valid Choice \n"); } } } void display(struct node* head) { if(head==NULL) { printf("\nThe list is empty \n"); } else { while(head!=NULL) { printf("*****************************************************\n"); printf("The employee Number :%d\n",head->emp_num); printf("The Employee Name : %s\n",head->name); printf("The Salary : %f\n",head->salary); printf("Years serviced : %d\n",head->Year_service); head=head->ptr; } } } struct node* createnode(struct node* head) { struct node* newnode = (struct node*)malloc(sizeof(struct node)); if(newnode == NULL) { printf("\nMemory allocation failed!\n"); return head; } printf("\nEnter the employee number \n"); scanf("%d",&newnode->emp_num); printf("Enter the employee name \n"); scanf("%s",newnode->name); printf("Enter the salary of the employee \n"); scanf("%f",&newnode->salary); printf("Enter the Employee Years of service \n"); scanf("%d",&newnode->Year_service); newnode->ptr=head; return newnode; } void search(struct node* head) { int target_num; int found = 0; // 标记是否找到匹配项 printf("\nEnter Employee Number\n"); scanf("%d", &target_num); while(head!=NULL) { if(target_num == head->emp_num) { found = 1; printf("\nThe element is matched\n"); printf("The employee Number : %d\n",head->emp_num); printf("The employee name : %s\n",head->name); printf("Salary : %f\n",head->salary); printf("Years serviced : %d\n",head->Year_service); // 员工编号唯一,找到后直接退出循环 break; } head=head->ptr; } // 遍历结束后统一判断是否找到 if(!found) { printf("\nThe element is not matched\n"); } }
关键修改点说明
切换为按员工编号搜索:
- 将搜索函数的输入从姓名字符串改为员工编号整数
target_num - 匹配逻辑从字符串比较
strcmp改为整数直接相等判断target_num == head->emp_num
- 将搜索函数的输入从姓名字符串改为员工编号整数
修复错误提示问题:
- 添加
found标记变量,初始为0表示未找到 - 找到匹配项时设置
found=1并跳出循环(员工编号唯一,无需继续遍历) - 仅在遍历完所有节点且未找到匹配时,才输出“未找到”提示,避免每一个不匹配节点都输出错误信息
- 添加
修复内存分配逻辑:
- 原
createnode函数中内存分配失败时访问空指针newnode->ptr的错误,修改为直接返回原头节点并提示内存分配失败
- 原
内容的提问来源于stack exchange,提问作者Seeni Mohd
相关产品推荐
相关产品推荐

