Fork me on GitHub

[leetcode-148-Sort List]

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

利用归并排序的思想,递归合并两个有序的链表。

首先将链表递归分成两部分,直到只有一个结点为止,然后从底到上合并链表。

当然是学习大牛代码后写出的,如下:

ListNode* merge(ListNode* l1, ListNode* l2)
    {//合并两个有序链表
        ListNode dumb(0);
        ListNode* cur = &dumb;
        while (l1 != NULL && l2 != NULL)
        {
            if (l1->val < l2->val)
            {
                cur->next = l1;
                l1 = l1->next;
            }
            else
            {
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }
        if (l1 != NULL)    cur->next = l1;            
        if (l2 != NULL)    cur->next = l2;    
        return dumb.next;
    }
    ListNode* sortList(ListNode* head)
    {//归并
        if (head == NULL || head->next == NULL) return head;
        
        ListNode* first = head;
        ListNode* second = head->next;
        while (second != NULL && second->next != NULL)
        {
            first = first->next;
            second = second->next->next;//每次移动两个结点
        }
        second = first->next;
        first->next = NULL;//将链表分成两个部分

        return merge(sortList(head), sortList(second));//递归操作
    }

 

posted @ 2017-02-24 19:45  hellowOOOrld  阅读(159)  评论(0编辑  收藏  举报