leetcode 148 排序链表

题目

在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

 

C++代码

/**
 * 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) {
         return merge_sort(head);   
    }
    ListNode* merge_sort(ListNode* head)
    {
        if(head == NULL || head->next == NULL)
            return head;
        ListNode *slow = head;
        ListNode *fast = head;
        ListNode *brek = head;
        while(fast->next)
        {
            brek = slow;
            slow = slow->next;
            fast = fast->next;
            if(fast->next)
                fast = fast->next;
        }
        brek->next = NULL;
        ListNode *l1 = merge_sort(head);
        ListNode *l2 = merge_sort(slow);
        return merge(l1, l2);
    }
    ListNode* merge(ListNode *l1, ListNode *l2)
    {
        ListNode* head = NULL;
        ListNode* p = NULL;
        while(l1)
        {
            if(l2)
            {
                if(l1->val < l2->val)
                {
                    if(head)
                        p->next = l1;
                    else
                        head = l1;
                    p = l1;
                    l1 = l1->next;
                }
                else
                {
                    if(head)
                        p->next = l2;
                    else
                        head = l2;
                    p = l2;
                    l2 = l2->next;
                }
            }
            else
            {
                if(head)
                    p->next = l1;
                else
                    head = l1;
                p = l1;
                l1 = l1->next;
            }
        }
        while(l2)
        {
            if(head)
                p->next = l2;
            else
                head = l2;
            p = l2;
            l2 = l2->next;
        }
        p->next = NULL;
        return head;
    }
};

 

posted @ 2019-08-15 21:28  xd_xumaomao  阅读(156)  评论(0编辑  收藏  举报