LeetCode—-Sort List
Question
Sort a linked list in O(n log n) time using constant space complexity.
Solution
看到对链表的排序,时间复杂度O(n log n),首先想到的就是归并排序。 但是这里其中有两个技巧:
- 就是将两个链表分开的时候,用到了fast-slow法,这是在处理链表分治,也就是找中间节点的一种有效方法。
- 还有就是merge的过程,也用到了递归的方式。
Code
/**
* 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)
return NULL;
if (head->next == NULL)
return head;
ListNode* p1 = head;
ListNode* p2 = head;
ListNode* pre = head;
// fast-slow 法
while (p2 != NULL && p2->next != NULL) {
pre = p1;
p1 = p1->next;
p2 = p2->next->next;
}
pre->next = NULL;
ListNode* L1 = sortList(head);
ListNode* L2 = sortList(p1);
return merge(L1, L2);
};
// merge 链表的方法,也用到了递归
ListNode* merge(ListNode* L1, ListNode* L2) {
if (L1 == NULL)
return L2;
if (L2 == NULL)
return L1;
if (L1->val <= L2->val) {
L1->next = merge(L1->next, L2);
return L1;
} else {
L2->next = merge(L1, L2->next);
return L2;
}
}
};