标签:accept list method mit 20px weight rtl http primary
Sort a linked list in O(n log n) time using constant space complexity.
Subscribe to see which companies asked this question
思路:
1.nlogn的排序算法有:快排、归并、堆排;
2.可是快排对链表不适合;
3.数组中归并的空间复杂度为O(n),可是链表能够直接归并仅仅须要O(1)的空间复杂度。
code:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *merge(ListNode *h1, ListNode *h2){ if(!h1) return h2; if(!h2) return h1; ListNode p(0); ListNode *t = &p; while(h1 && h2){ if(h1->val < h2->val){ t->next = h1; h1 = h1->next; }else{ t->next = h2; h2 = h2->next; } t = t->next; } t->next = h1 ? h1:h2; return p.next; } ListNode* sortList(ListNode* head) { // 空或仅仅有一个结点,直接返回 if(!head || !head->next) return head; // 利用快、慢指针找到中间结点 ListNode *slow = head,*fast = head; while(fast && fast->next && fast->next->next){ slow = slow->next; fast = fast->next->next; } ListNode *h2 = sortList(slow->next); // 后半部分 slow -> next = NULL; // 这里要先断链才干进行前半部分的归并 ListNode *h1 = sortList(head); // 前半部分 return merge(h1,h2); } };
标签:accept list method mit 20px weight rtl http primary
原文地址:http://www.cnblogs.com/mfmdaoyou/p/7275543.html