Sort List

思路:使用归并排序的方法,注意寻找的中间节点位置

/**
 * 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 == nullptr || head->next == nullptr)
            return head;
        
        ListNode *first = head, *second = head;
        while(first->next && first->next->next)
        {
            first = first->next->next;
            second = second->next;
        }
        
        ListNode *mid = second->next;
        second->next = nullptr;
        ListNode *l1 = sortList(head);
        ListNode *l2 = sortList(mid);
        
        return mergeTwoLists(l1, l2);
    }
    
    ListNode* mergeTwoLists(ListNode *l1, ListNode *l2)
    {
        ListNode dummy(-1);
        ListNode *cur = &dummy;
        
        while(l1 != nullptr && l2 != nullptr)
        {
            if(l1->val < l2->val)
            {
                cur->next = l1;
                l1 = l1->next;
            }
            else
            {
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }
        
        cur->next = (l1 == nullptr) ? l2 : l1;
        
        return dummy.next;
    }
};

 

posted @ 2017-03-31 09:06  chengcy  Views(140)  Comments(0)    收藏  举报