最近学了链表,晚上想要写一个链表的冒泡排序,一开始没有大的头绪,在网上查找了一翻也差强人意,大多写得十分复杂,可读性很差,于是自己写了一个,如果有后来者碰到类似的疑惑,或许可以提供一点帮助,代码的讲解就在注释里面了,因为是自己写着玩,所以也没有封装函数,如果有兴趣,可以自己改改
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
int main() {
struct node *head, *p, *q, *t, *temp2;
int n, a, temp;
head = NULL;
scanf("%d", &n);//输入总的个数
for (int i = 0; i < n; i++) { //创建链表
p = (struct node*) malloc(sizeof (struct node));
scanf("%d", &a);
p->data = a;
if(head == NULL)
{
head = p;
}else
{
q->next = p;
p->next = NULL;
}
q = p;
}
t = head;
while (t != NULL) //打印链表数据
{
printf("%d ", t->data);
t = t->next;
}
printf("\n");
t = head;
temp2 = NULL; //temp2=NULL是为了让第一次比较会一直走到链表的最后一个元素
while (temp2 != head->next) { //当temp2来到第二个元素时,则所有元素都已经归位,排序完成,看不懂比较条件继续往下看
if(t != NULL) {
if (t->data > t->next->data) { //比较相邻的两个数大小,将大的那一个向后移动
temp = t->data;
t->data = t->next->data;
t->next->data = temp; //交换位置
}
}
t = t->next; //将比较的元素依次向后移动
if (t->next == temp2) { //使用一个参数temp2,来限制比较的移动位置,已经归位的无需比较,逐渐减小比较次数
temp2 = t; //将正确归位的元素的地址赋给temp2,下一次比较到这个元素前面的时候,就无需进行比较,回到第一个元素,开始新的一轮排序
t = head;
}
}
t = head;
while (t != NULL) //打印链表数据
{
printf("%d ", t->data);
t = t->next;
}
printf("\n");
return 0;
}