LeetCode——Sort List

Question

Sort a linked list in O(n log n) time using constant space complexity.

Solution

分析,时间复杂度要求为nlogn,因此得考虑归并排序,但是空间必须为常量,因此得注意指针的操作。

Code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if (head == NULL)
            return head;
        if (head->next == NULL)
            return head;
        ListNode* p1 = head;
        ListNode* p2 = head;
        ListNode* pre = head;
        
        // fast and slow 两个指针,用于找到中间节点
        // pre节点,需要把链表断开,生成两个链表
        while ( p2 != NULL && p2->next != NULL) {
            pre = p1;
            p1 = p1->next;
            p2 = p2->next->next;
        }
        pre->next = NULL;
        
        ListNode* l1 = sortList(head);
        ListNode* l2 = sortList(p1);
        
        return merge(l1, l2);
        
    }
    ListNode* merge(ListNode* l1, 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;
        }
            
    }
};
原文地址:https://www.cnblogs.com/zhonghuasong/p/7695907.html