举一个C语言链表由大到小排序的实际例子
时间: 2023-07-25 11:13:06 浏览: 95
假设有一个学生信息的链表,包含学生的姓名和分数,现在需要按照分数从大到小的顺序对链表进行排序。以下是一个C语言链表排序的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student {
char name[20];
int score;
struct student *next;
} Student;
/* 插入排序 */
void insert_sort(Student *head) {
Student *p, *q, *pre, *temp;
p = head->next;
head->next = NULL;
while (p != NULL) {
temp = p;
p = p->next;
pre = head;
q = head->next;
while (q != NULL && q->score > temp->score) {
pre = q;
q = q->next;
}
temp->next = q;
pre->next = temp;
}
}
int main() {
Student *head, *p, *temp;
head = (Student *)malloc(sizeof(Student));
head->next = NULL;
int n, i;
char name[20];
int score;
printf("请输入学生个数:");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("请输入第%d个学生的信息:\n", i + 1);
printf("姓名:");
scanf("%s", name);
printf("分数:");
scanf("%d", &score);
temp = (Student *)malloc(sizeof(Student));
strcpy(temp->name, name);
temp->score = score;
temp->next = NULL;
p = head;
while (p->next != NULL && p->next->score > score) {
p = p->next;
}
temp->next = p->next;
p->next = temp;
}
insert_sort(head);
printf("排序后的学生信息:\n");
p = head->next;
while (p != NULL) {
printf("%s %d\n", p->name, p->score);
p = p->next;
}
return 0;
}
```
在这个示例中,我们使用了插入排序算法对链表进行排序。具体来说,我们将链表分为已排序部分和未排序部分,然后每次从未排序部分中取出一个节点,插入到已排序部分中的适当位置。这样,最终就能得到一个有序的链表。
阅读全文