1. 程式人生 > >LeetCode 148. Sort List

LeetCode 148. Sort List

歸並 定時 public con span def pre const nullptr

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

題目要求給定時間復雜度對鏈表進行排序,但是我個人認為題目要求不是很合理,使用歸並排序時間復雜度滿足要求,但是空間復雜度並不為常數,所以個人認為這道題不嚴謹,說實話,對鏈表進行歸並排布的代碼涉及到遞歸,我還不是很熟悉,先貼上吧,日後再認真學習:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* sortList(ListNode* head) { 12 if (!head || !head->next) 13 return head; 14 ListNode *fast = head, *slow = head, *pre = head; 15 while (fast && fast->next)
16 { 17 pre = slow; 18 slow = slow->next; 19 fast = fast->next->next; 20 } 21 pre->next = nullptr; 22 return merge(sortList(head), sortList(slow)); 23 } 24 25 ListNode *merge(ListNode* l1, ListNode *l2) 26 {
27 ListNode *dummy = new ListNode(-1); 28 ListNode *cur = dummy; 29 while (l1 && l2) 30 { 31 if (l1->val < l2->val) 32 { 33 cur->next = l1; 34 l1 = l1->next; 35 } 36 else 37 { 38 cur->next = l2; 39 l2 = l2->next; 40 } 41 cur = cur->next; 42 } 43 if (l1) 44 cur->next = l1; 45 if (l2) 46 cur->next = l2; 47 return dummy->next; 48 } 49 };

LeetCode 148. Sort List