C语言链表冒泡排序算法实现 - 学生信息排序
#include <stdio.h> #include <stdlib.h> #include <string.h>
struct student { int id; char name[20]; float score; struct student *next; };
// 创建链表 struct student *create_list() { struct student *head, *p, *tail; head = (struct student *)malloc(sizeof(struct student)); tail = head; tail->next = NULL; int id; char name[20]; float score; printf('请输入学号、姓名、成绩(以-1结束):\n'); scanf('%d', &id); while (id != -1) { scanf('%s%f', name, &score); p = (struct student *)malloc(sizeof(struct student)); p->id = id; strcpy(p->name, name); p->score = score; tail->next = p; tail = p; tail->next = NULL; scanf('%d', &id); } return head; }
// 输出链表 void print_list(struct student *head) { struct student *p = head->next; while (p) { printf('%d\t%s\t%.2f\n', p->id, p->name, p->score); p = p->next; } }
// 链表冒泡排序 void bubble_sort(struct student *head) { struct student *p, *q, *tail; tail = NULL; while (head->next != tail) { p = head; q = p->next; while (q->next != tail) { if (q->score < q->next->score) { p->next = q->next; q->next = q->next->next; p->next->next = q; } p = p->next; q = p->next; } tail = q; } }
int main() { struct student *head; head = create_list(); printf('\n原始链表:\n'); print_list(head); bubble_sort(head); printf('\n排序后的链表:\n'); print_list(head); return 0;
原文地址: https://www.cveoy.top/t/topic/oEzx 著作权归作者所有。请勿转载和采集!