LeetCode:Sort a linked list in O(n log n) time using constant space complexity(链表归并排序)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liuweiyuxiang/article/details/87897586

有关归并排序算法的理解参考博客:剑指offer:归并排序与数组中的逆序对.在这里结合leetcode上的题目给出归并排序的C++实现。
题目:Sort a linked list in O(n log n) time using constant space complexity
思路:
因为题目要求复杂度为O(nlogn),故可以考虑归并排序的思想。
归并排序的一般步骤为:
1)将待排序数组(链表)取中点并一分为二;
2)递归地对左半部分进行归并排序;
3)递归地对右半部分进行归并排序;
4)将两个半部分进行合并(merge),得到结果。

所以对应此题目,可以划分为三个小问题:
1)找到链表中点 (快慢指针思路,快指针一次走两步,慢指针一次走一步,快指针在链表末尾时,慢指针恰好在链表中点);
2)写出merge函数,即如何合并链表。 (见merge-two-sorted-lists 一题解析)
3)写出mergesort函数,实现上述步骤。
代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode * mergeList(ListNode *list1, ListNode *list2){
        ListNode * nhead = new ListNode(0);
        ListNode * cur = nhead;
        while(list1 && list2){
            if(list1->val < list2->val){
                cur->next = list1;
                list1 = list1->next;
            }else{
                cur->next = list2;
                list2 = list2->next;
            }
            cur = cur->next;
        }
        if(list1 != NULL)
            cur->next = list1;
        if(list2 != NULL)
            cur->next = list2;
        return nhead->next;
    }
    //使用归并排序,首先使用快慢指针的思想,将链表一分为二,然后归并
    ListNode *sortList(ListNode *head) {
        if(head == NULL || head->next == NULL)
            return head;
        ListNode *slow = head;
        ListNode *fast = head->next;
        while(fast && fast->next){
            fast = fast->next->next;
            slow = slow->next;
        }
        ListNode *headb = slow->next;
        slow->next = NULL;
        ListNode *right = sortList(headb);
        ListNode *left = sortList(head);
        return mergeList(right, left);
    }
};

猜你喜欢

转载自blog.csdn.net/liuweiyuxiang/article/details/87897586