链表冒泡排序已知结构体类型 struct student的成员变量是学号姓名和成绩编程创建链表函数输出链表值函数和链表冒泡排序函数。
以下是链表冒泡排序的实现代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student {
int id; // 学号
char name[20]; // 姓名
int score; // 成绩
struct student *next; // 指向下一个结点的指针
};
// 创建链表函数
struct student *create_list(int n) {
struct student *head, *p, *tail;
head = (struct student *)malloc(sizeof(struct student)); // 创建头结点
tail = head;
for (int i = 0; i < n; i++) {
p = (struct student *)malloc(sizeof(struct student)); // 创建新结点
printf("请输入第%d个学生的学号、姓名和成绩:", i + 1);
scanf("%d %s %d", &p->id, p->name, &p->score);
tail->next = p; // 将新结点连接到链表尾部
tail = p; // 将链表尾指针指向新结点
}
tail->next = NULL; // 将链表尾结点指向NULL
return head;
}
// 输出链表值函数
void print_list(struct student *head) {
struct student *p = head->next; // 指向链表第一个结点
while (p != NULL) {
printf("%d %s %d\n", p->id, p->name, p->score);
p = p->next; // 指向下一个结点
}
}
// 链表冒泡排序函数
void bubble_sort(struct student *head, int n) {
struct student *p, *q, *end = NULL;
for (int i = 0; i < n - 1; i++) {
p = head->next;
q = p->next;
while (q != end) {
if (p->score > q->score) { // 如果当前结点的成绩比下一个结点的成绩大,则交换两个结点的数据
int id = p->id;
char name[20];
strcpy(name, p->name);
int score = p->score;
p->id = q->id;
strcpy(p->name, q->name);
p->score = q->score;
q->id = id;
strcpy(q->name, name);
q->score = score;
}
p = p->next;
q = q->next;
}
end = p; // 将end指向已排好序的结点,减少比较次数
}
}
int main() {
int n;
printf("请输入学生数量:");
scanf("%d", &n);
struct student *head = create_list(n);
printf("排序前的链表值:\n");
print_list(head);
bubble_sort(head, n);
printf("排序后的链表值:\n");
print_list(head);
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/hbkK 著作权归作者所有。请勿转载和采集!