建立一个学生成绩信息(包括学号、姓名、成绩)的单向链表,学生记录按学号由小到大顺序排列,要求实现对成绩信息的插入、修改、删除和遍历操作
1条回答 默认 最新
- 技术专家团-小桥流水 2021-12-14 21:59关注
链表的增删改遍历,代码如下,如有帮助,请帮忙采纳一下,谢谢。
#include <stdio.h> #include <stdlib.h> struct Student { int id; char name[20]; int score; struct Student* next; }; //创建链表,按学号排序插入 struct Student* createlist() { int i,n; struct Student* head,*pre,*p,*t; head = (struct Student*)malloc(sizeof(struct Student)); head->next = NULL; printf("请输入学生的个数:"); scanf("%d",&n); for(i=0;i<n;i++) { t = (struct Student*)malloc(sizeof(struct Student)); t->next = NULL; printf("请输入学生%d的学号:",i+1); scanf("%d",&t->id); printf("请输入学生%d的姓名:",i+1); scanf("%s",t->name); printf("请输入学生%d的成绩:",i+1); scanf("%d",&t->score); pre = head; p = pre->next; while (pre && p) { if(p->id < t->id) { pre = p; p = p->next; }else break; } if(p) { pre->next = t; t->next = p; }else pre->next = t; } return head; } //遍历显示 void show(struct Student* head) { struct Student* p; if(head == 0) { printf("链表为空\n"); return; } p=head->next; while(p) { printf("学号:%d 姓名:%s 成绩:%d\n",p->id,p->name,p->score); p = p->next; } } //插入 struct Student* insert(struct Student* head) { struct Student *pre,*p,*t; t = (struct Student*)malloc(sizeof(struct Student)); t->next = NULL; printf("请输入学生的学号:"); scanf("%d",&t->id); printf("请输入学生的姓名:"); scanf("%s",t->name); printf("请输入学生的成绩:"); scanf("%d",&t->score); pre = head; p = pre->next; while (pre && p) { if(p->id < t->id) { pre = p; p = p->next; }else break; } if(p) { pre->next = t; t->next = p; }else pre->next = t; return head; } //修改 struct Student* mod(struct Student* head) { struct Student* p = head->next; int id; printf("请输入要修改信息的学生学号:"); scanf("%d",&id); while(p) { if(p->id == id) break; else p = p->next; } printf("请输入学生的姓名:"); scanf("%s",p->name); printf("请输入学生的成绩:"); scanf("%d",&p->score); return head; } //删除 struct Student* del(struct Student* head) { struct Student* p,*pre; int id; pre = head; p = head->next; printf("请输入要修改信息的学生学号:"); scanf("%d",&id); while(p) { if(p->id == id) break; else { pre = p; p = p->next; } } if(p) { pre->next = p->next; free(p); p=0; printf("删除成功\n"); }else printf("未找到该学号的学生\n"); return head; } //释放内存 void release(struct Student* head) { struct Student *p; while(head) { p = head->next; free(head); head = p; } } int main() { struct Student* head =NULL; head = createlist(); printf("当前链表数据为:\n"); show(head); printf("插入数据:"); head = insert(head); printf("插入数据后:\n"); show(head); printf("修改数据:"); head = mod(head); printf("修改数据后:\n"); show(head); printf("删除数据\n"); head = del(head); printf("删除数据后:\n"); show(head); //释放内存 release(head); return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 8无用 3