[链表]单链表的排序

92 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

问题

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

思路

将链表递归对半拆成一个个节点后,再将节点连接。

代码实现

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    ListNode* sortInList(ListNode* head) {
        // write code here
        if (head == NULL || head->next == NULL) return head;
        ListNode* left = head;
        ListNode* mid = head->next;
        ListNode* right = head->next->next;
        // 找到中间节点
        while (right && right->next)
        {
            left = left->next;
            mid = mid->next;
            right = right->next->next;
        }
        // 将链表分成两段
        left->next = NULL;
        return merge(sortInList(head), sortInList(mid));
    }
    ListNode* merge(ListNode* head1, ListNode* head2)
    {
        ListNode* dummyHead = new ListNode(0);
        ListNode* cur = dummyHead;
        
        while (head1 && head2)
        {
            if (head1->val < head2->val)
            {
                cur->next = head1;
                head1 = head1->next;
            }
            else
            {
                cur->next = head2;
                head2 = head2->next;
            }
            cur = cur->next;
        }
        if (head1) cur->next = head1;
        if (head2) cur->next = head2;
        
        return dummyHead->next;
    }
};