利用链表来实现对员工信息的存储,排序,删除,插入
这个问题很简单,但是它涉及的面很广,所以很具有学习的意义。
#include<stdio.h> #include<string.h> #include<stdlib.h> struct Emplyee { int num; char name[20]; int age; struct Emplyee * next; }; void main() { struct Emplyee * Create(); void Output(struct Emplyee *); struct Emplyee * Sort(struct Emplyee *); struct Emplyee * Insert(struct Emplyee *, struct Emplyee *); struct Emplyee * Delete(struct Emplyee *, char name[20]); struct Emplyee * s = Create(); Output(s); printf("排序后的结果为:\n"); s = Sort(s); Output(s); struct Emplyee my = { 21, "John", 24 }; printf("插入后的结果为:\n"); s = Insert(s, &my); Output(s); printf("删除后的结果为:\n"); s = Delete(s, "John"); Output(s); getchar(); } struct Emplyee * Create() { struct Emplyee * s; struct Emplyee * p = NULL; printf("输入三个员工的名字:\n"); for (int i = 0; i < 3; i++) { s = (struct Emplyee *)malloc(sizeof(struct Emplyee)); s->num = i; gets(s->name); s->age = 21 + i; if (p == NULL) { s->next = NULL; p = s; } else { s->next = p; p = s; } } return p; } void Output(struct Emplyee * sl) { while (sl) { printf("工号:%d\t姓名:%s\t年龄:%d\n", sl->num, sl->name, sl->age); sl = sl->next; } } struct Emplyee * Sort(struct Emplyee * s) { struct Emplyee temp, *last, *first, *p = s; for (int i = 0; i < 3; i++) { p = s; for (int j = 0; j<i; j++) { p = p->next; } first = p; struct Emplyee * min = p; while (p!= NULL) { if (p->age <min->age) { min = p; } p = p->next; } temp = *min; min->age = first->age; min->num = first->num;
strcpy(min->name,first->name); first->age = temp.age; first->num = temp.num;
strcpy(first->name,temp.name); } return s; } struct Emplyee * Insert(struct Emplyee * s, struct Emplyee * t) { struct Emplyee * p = NULL; struct Emplyee * q = s; while ((q->age < t->age) && q->next != NULL) { p = q; q = q->next; } if (t->age<=q->age)//说明不是在尾部插入 { if (s == q)//链表是空的 { p = t; p->next = NULL; } else { p->next = t; } t->next = q; } else//说明是在尾部进行插入 { q->next = t; t->next = NULL; } return s; } struct Emplyee * Delete(struct Emplyee * s, char name[20]) { struct Emplyee * p1 = NULL, *p2 = NULL; p1 = s; while ((strcmp(p1->name, name)) && p1->next != NULL) { p2 = p1; p1 = p1->next; } if (!(strcmp(p1->name, name))) { if (p1 == s) { s = p1->next; } else { p2->next = p1->next; } //free(p1);这个可能是编译器的问题,我只要使用,编译器就会提示我触动了断点,而事实上,我并未打任何断点。 } return s; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话