标签:复杂度 排序 slow turn 归并排序 lin val constant int
Sort a linked list in O(n log n) time using constant space complexity.
解题思路:归并排序的思想,空间复杂度其实是O(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 || !head->next)return head; ListNode* fast = head, *slow = head, *pre = NULL; while(fast && fast->next) { pre = slow; slow = slow->next; fast = fast->next->next; } pre->next = NULL; ListNode* l1 = sortList(head); ListNode* l2 = sortList(slow); return merge(l1, l2); } ListNode* merge(ListNode* l1, ListNode* l2) { ListNode* l = new ListNode(0), *tail=l; while(l1 && l2) { if(l1->val > l2->val) { tail->next = l2; tail = l2; l2=l2->next; } else { tail->next = l1; tail = l1; l1 = l1->next; } } if(l1)tail->next = l1; else tail->next=l2; return l->next; } };
标签:复杂度 排序 slow turn 归并排序 lin val constant int
原文地址:http://www.cnblogs.com/tsunami-lj/p/7707113.html