首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

链表的合并排序代码只对C语言中一半的元素进行排序

链表的合并排序是一种常见的排序算法,用于对链表中的元素进行排序。该算法将链表分为两个部分,然后分别对这两个部分进行排序,最后将两个有序的链表合并成一个有序的链表。

以下是一个示例的链表合并排序的代码实现:

代码语言:txt
复制
#include <stdio.h>
#include <stdlib.h>

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

// 合并两个有序链表
struct ListNode* merge(struct ListNode* l1, struct ListNode* l2) {
    if (l1 == NULL) {
        return l2;
    }
    if (l2 == NULL) {
        return l1;
    }

    if (l1->val < l2->val) {
        l1->next = merge(l1->next, l2);
        return l1;
    } else {
        l2->next = merge(l1, l2->next);
        return l2;
    }
}

// 拆分链表
struct ListNode* split(struct ListNode* head) {
    if (head == NULL || head->next == NULL) {
        return head;
    }

    struct ListNode* slow = head;
    struct ListNode* fast = head->next;

    while (fast != NULL && fast->next != NULL) {
        slow = slow->next;
        fast = fast->next->next;
    }

    struct ListNode* secondHalf = slow->next;
    slow->next = NULL;

    return secondHalf;
}

// 链表的合并排序
struct ListNode* mergeSort(struct ListNode* head) {
    if (head == NULL || head->next == NULL) {
        return head;
    }

    struct ListNode* secondHalf = split(head);

    head = mergeSort(head);
    secondHalf = mergeSort(secondHalf);

    return merge(head, secondHalf);
}

// 创建链表节点
struct ListNode* createNode(int val) {
    struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
    newNode->val = val;
    newNode->next = NULL;
    return newNode;
}

// 打印链表
void printList(struct ListNode* head) {
    struct ListNode* temp = head;
    while (temp != NULL) {
        printf("%d ", temp->val);
        temp = temp->next;
    }
    printf("\n");
}

int main() {
    // 创建链表
    struct ListNode* head = createNode(4);
    head->next = createNode(2);
    head->next->next = createNode(1);
    head->next->next->next = createNode(3);

    printf("原始链表:");
    printList(head);

    // 链表的合并排序
    head = mergeSort(head);

    printf("排序后链表:");
    printList(head);

    return 0;
}

以上代码实现了链表的合并排序。首先,通过拆分链表的方式将链表分为两个部分,然后递归地对这两个部分进行排序。最后,通过合并两个有序链表的方式将两个部分合并成一个有序的链表。

链表的合并排序算法的时间复杂度为O(nlogn),其中n是链表的长度。该算法在处理大规模数据时具有较好的性能。

推荐的腾讯云相关产品:腾讯云云服务器(https://cloud.tencent.com/product/cvm)

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券