Sort List问题及解法

来源:互联网 发布:jsmd5解密算法 编辑:程序博客网 时间:2024/05/18 21:07

问题描述:

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

问题分析:

根据题意,归并法的时间复杂度为O(n log n) ,故采用归并法求解。求解过程中最重要是如何将链表均分成两组,这里采用双指针法。


过程详见代码:

/** * 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 || head->next == NULL) return head;ListNode* prev = NULL, *slow = head, *fast = head;while (fast != NULL &&fast->next != NULL){prev = slow;slow = slow->next;fast = fast->next->next;}prev->next = NULL;ListNode* l1 = sortList(head);ListNode* l2 = sortList(slow);return merge(l1, l2);}ListNode* merge(ListNode* h1, ListNode* h2){if (h1 == NULL){return h2;}if (h2 == NULL){return h1;}if (h1->val < h2->val){h1->next = merge(h1->next, h2);return h1;}else{h2->next = merge(h1, h2->next);return h2;}}};