c语言实现链表的冒泡排序

最近学了链表,晚上想要写一个链表的冒泡排序,一开始没有大的头绪,在网上查找了一翻也差强人意,大多写得十分复杂,可读性很差,于是自己写了一个,如果有后来者碰到类似的疑惑,或许可以提供一点帮助,代码的讲解就在注释里面了,因为是自己写着玩,所以也没有封装函数,如果有兴趣,可以自己改改

#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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值