C语言链表排序

        刚刚在做C语言作业,需要对链表排序,本来想偷懒来CSDN抄一个的,也许是我点背,试了几个都不对,要么是死循环,要么就排序结果根本不对,愤懑之下决定自己用冒泡排序写一个对链表排序的函数分享在这里,希望不要再有人拿着自己错误的代码在这里浪费平台的资源和别人的时间。

#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>

// 定义链表节点结构
struct Node {
    int data;
    struct Node* next;
};

// 创建新节点
struct Node* createNode(int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 插入节点到链表尾部
void insertNode(struct Node** head, int data) {
    struct Node* newNode = createNode(data);
    if (*head == NULL) {
        *head = newNode;
    } else {
        struct Node* current = *head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newNode;
    }
}

// 输出链表
void printList(struct Node* head) {
    struct Node* current = head;
    while (current != NULL) {
        printf("%d -> ", current->data);
        current = current->next;
    }
    printf("NULL\n");
}

// 链表排序函数(冒泡排序)
void sortList(struct Node* head) {
    struct Node* current;
    struct Node* index = NULL;
    int temp;

    if (head == NULL) {
        return;
    }

    do {
        current = head;
        while (current->next != index) {
            if (current->data > current->next->data) {
                // 交换节点数据
                temp = current->data;
                current->data = current->next->data;
                current->next->data = temp;
            }
            current = current->next;
        }
        index = current;
    } while (index != head->next);
}

// 主函数
int main() {
    struct Node* head = NULL;

    // 插入节点
    insertNode(&head, 5);
    insertNode(&head, 3);
    insertNode(&head, 8);
    insertNode(&head, 1);
    insertNode(&head, 6);

    // 输出未排序的链表
    printf("未排序的链表:\n");
    printList(head);

    // 对链表进行排序
    sortList(head);

    // 输出排序后的链表
    printf("排序后的链表:\n");
    printList(head);
    system("pause");
    return 0;
}

  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

归闲先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值