sort-list——鏈表、快慢指針找中間、歸並排序
阿新 • • 發佈:2017-06-07
val 排序。 rtl != spa 判斷 nbsp node ace
Sort a linked list in O(n log n) time using constant space complexity.
鏈表,快慢指針找中點,歸並排序。
註意判斷條件fast->next!=NULL&&fast->next->next!=NULL,若為fast!=NULL&&fast->next!=NULL則會出現內存溢出
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==NULL || head->next==NULL) 13 return head; 14 ListNode* slow, *fast; 15 slow=head; 16 fast=head; 17 while(fast->next!=NULL&&fast->next->next!=NULL){ 18 slow=slow->next; 19 fast=fast->next->next; 20 } 21 fast=slow; 22 slow=slow->next; 23 fast->next=NULL; 24 fast=sortList(head); 25 slow=sortList(slow);26 return merge(fast,slow); 27 28 } 29 ListNode *merge(ListNode *left, ListNode *right){ 30 ListNode *res,*temp; 31 if(left==NULL){ 32 res=right; 33 return res; 34 } 35 if(right==NULL){ 36 res=left; 37 return res; 38 } 39 if(left->val<=right->val){ 40 res=left; 41 left=left->next; 42 }else{ 43 res=right; 44 right=right->next; 45 } 46 temp=res; 47 while(left!=NULL&&right!=NULL){ 48 if(left->val<=right->val){ 49 temp->next=left; 50 left=left->next; 51 }else{ 52 temp->next=right; 53 right=right->next; 54 } 55 temp=temp->next; 56 57 } 58 if(left!=NULL){ 59 temp->next=left; 60 } 61 if(right!=NULL){ 62 temp->next=right; 63 } 64 return res; 65 } 66 };
sort-list——鏈表、快慢指針找中間、歸並排序