题目要求:
Sort a linked list in O(n log n) time using constant space complexity.
满足O(n log n)时间复杂度的有快排、归并排序、堆排序。在这里采用的是归并排序(空间复杂度O(log n)),具体程序如下:
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* merge(ListNode* l1, ListNode* l2) 12 { 13 ListNode *dummy = new ListNode(0); 14 ListNode *head = nullptr, *start = dummy; 15 while(l1 && l2) 16 { 17 if(l1->val < l2->val) 18 { 19 start->next = l1; 20 l1 = l1->next; 21 } 22 else 23 { 24 start->next = l2; 25 l2 = l2->next; 26 } 27 start = start->next; 28 } 29 30 if(!l1) 31 start->next = l2; 32 else if(!l2) 33 start->next = l1; 34 35 head = dummy->next; 36 delete dummy; 37 dummy = nullptr; 38 39 return head; 40 } 41 42 ListNode* mergeSort(ListNode* head) 43 { 44 if(!head->next) 45 return head; 46 47 ListNode *slow = head, *fast = head; 48 ListNode *preNode = slow; 49 while(fast && fast->next) 50 { 51 preNode = slow; 52 slow = slow->next; 53 fast = fast->next->next; 54 } 55 preNode->next = nullptr; 56 57 ListNode *left = mergeSort(head); 58 ListNode *right = mergeSort(slow); 59 return merge(left, right); 60 } 61 62 ListNode* sortList(ListNode* head) { 63 if(!head || !head->next) 64 return head; 65 66 return mergeSort(head); 67 } 68 };
时间: 2024-10-13 11:38:34