OJ题之单链表排序

描述

给定一个节点数为n的无序单链表,对其按升序排序。

数据范围:0<n≤1000000<n≤100000,保证节点权值在[−109,109][−109,109]之内。

要求:空间复杂度 O(n),时间复杂度 O(nlogn)

给出以下三种方式:

1. 冒泡排序

通过重复遍历链表,比较相邻元素并交换位置,直到整个链表有序。

cpp 复制代码
void bubbleSort(ListNode* head) {
    if (!head) return;
    bool swapped;
    do {
        swapped = false;
        ListNode* current = head;
        while (current->next) {
            if (current->val > current->next->val) {
                std::swap(current->val, current->next->val);
                swapped = true;
            }
            current = current->next;
        }
    } while (swapped);
}

2. 选择排序

每次遍历链表找到最小元素,将其与当前元素交换位置。

cpp 复制代码
void selectionSort(ListNode* head) {
    for (ListNode* current = head; current; current = current->next) {
        ListNode* minNode = current;
        for (ListNode* nextNode = current->next; nextNode; nextNode = nextNode->next) {
            if (nextNode->val < minNode->val) {
                minNode = nextNode;
            }
        }
        std::swap(current->val, minNode->val);
    }
}

3. 合并排序

采用分治法,将链表分成两半,递归地排序每一半,然后合并两个已排序的链表。

cpp 复制代码
ListNode* merge(ListNode* l1, ListNode* l2) {
    ListNode dummy(0);
    ListNode* tail = &dummy;
    while (l1 && l2) {
        if (l1->val < l2->val) {
            tail->next = l1;
            l1 = l1->next;
        } else {
            tail->next = l2;
            l2 = l2->next;
        }
        tail = tail->next;
    }
    tail->next = l1 ? l1 : l2;
    return dummy.next;
}

ListNode* mergeSort(ListNode* head) {
    if (!head || !head->next) return head;
    ListNode* slow = head;
    ListNode* fast = head->next;
    while (fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;
    }
    ListNode* mid = slow->next;
    slow->next = nullptr;
    return merge(mergeSort(head), mergeSort(mid));
}
相关推荐
quaer1 分钟前
如何理解矩阵的复数特征值和特征向量?
算法
并不会13 分钟前
“从零开始学排序:简单易懂的算法指南“
java·数据结构·学习·算法·排序算法·重要知识
LuckyRich132 分钟前
【贪心算法】贪心算法二
算法·贪心算法
黑牛先生37 分钟前
【C++】AVL树
算法
fzzf59237 分钟前
Codeforces Round 976 (Div. 2) and Divide By Zero 9.0(A~E)
数据结构·c++·算法
weixin_4866811442 分钟前
C++系列-STL容器中的排序算法
c++·算法·排序算法
speop44 分钟前
【笔记】数据结构12
数据结构·笔记
蠢蠢的打码1 小时前
8622 哈希查找
数据结构·c++·算法·链表·图论
Starry_hello world2 小时前
单链表(纯代码)
数据结构·笔记·有问必答