用单链表实现学生成绩的crud
#include<iostream> using namespace std; typedef struct node { char name[10]; int score; struct node* next; }StudList; void CreateStudent(StudList*& sl);//采用交互式方式创建学生单链表 void DestoryList(StudList*& L);//销毁学生单链表 void DispList(StudList* L);//输出学生单链表 void SortList(StudList*& L);//将学生单链表按成绩递减排序 int main() { StudList* st; printf("(1)建立学生单链表\n"); CreateStudent(st); printf("(2)按成绩递减排序\n"); SortList(st); printf("(3)排序后的结果\n"); DispList(st); printf("(4)销毁学生单链表\n"); DestoryList(st); return 0; } void CreateStudent(StudList* &sl) {//尾插法 int n; StudList* stu, * tc; sl = (StudList*)malloc(sizeof(StudList));//创建头结点 tc = sl;//tc始终指向尾结点,开始时指向头节点; printf("学生人数:"); scanf_s("%d", &n); for (int i = 0; i < n; i++) { stu = (StudList*)malloc(sizeof(StudList));//创建新结点 printf("第%d个学生姓名和成绩:", i + 1); scanf_s("%s %d\n", stu->name, &stu->score); tc->next = stu;//将stu插入tc之后 tc = stu; } tc->next = NULL; } void DestoryList(StudList*& L) {//据我判断是从头删除 StudList* pre = L, * p = pre->next; while (p != NULL) { free(pre); pre = p; p = p->next; } free(p); } void DispList(StudList* L) {//输出 StudList* p = L->next; int i = 1; printf(" 名次 姓名 成绩\n"); while (p != NULL) { printf(" %d\t\t", i++); printf("%s\t\t", p->name); printf("%d\n", p->score); p = p->next; } } void SortList(StudList*& L) { StudList* p, * pre, * q; p = L->next->next;//p指向L的第2个数据结点 //这个表有三格,前两格放name,score,第三格是指针域 L->next->next = NULL;//构造只含一个数据节点的有序表 while (p != NULL) { q = p->next; //q保存p结点后继结点的指针 pre = L; //从有序表开头进行比较,pre指向插入p的前驱节点 while (pre->next != NULL && pre->next->score > p->score) { pre = pre->next; //在有序表中找插入p的前驱节点pre } p->next = pre->next; //将pre之后插入p pre->next = p; p = q; //扫描原单链表余下的结点 } }