sort-list--linked list, fast and slow pointer to find the middle, merge sort

Source: Internet
Author: User


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

Linked list, fast and slow pointer to find the midpoint, merge sort.

Pay attention to judging condition fast->next!=null&&fast->next->next!=null, if fast!=null&&fast->next!= Null will cause a memory overflow

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 classSolution {Ten  Public: OneListNode *sortlist (ListNode *head) { A         if(Head==null | | head->next==NULL) -             returnhead; -listnode* Slow, *fast; theslow=head; -fast=head; -          while(fast->next!=null&&fast->next->next!=NULL) { -Slow=slow->Next; +Fast=fast->next->Next; -         } +fast=slow; ASlow=slow->Next; atfast->next=NULL; -fast=Sortlist (head); -slow=sortlist (slow); -         returnmerge (Fast,slow); -          -     } inListNode *merge (ListNode *left, ListNode *Right ) { -ListNode *res,*temp; to         if(left==NULL) { +res=Right ; -             returnRes; the         } *         if(right==NULL) { $res=Left ;Panax Notoginseng             returnRes; -         } the         if(left->val<=right->val) { +res=Left ; ALeft=left->Next; the}Else{ +res=Right ; -Right=right->Next; $         } $temp=Res; -          while(left!=null&&right!=NULL) { -             if(left->val<=right->val) { thetemp->next=Left ; -Left=left->Next;Wuyi}Else{ thetemp->next=Right ; -Right=right->Next; Wu             } -Temp=temp->Next; About              $         } -         if(left!=NULL) { -temp->next=Left ; -         } A         if(right!=NULL) { +temp->next=Right ; the         } -         returnRes; $     } the};

sort-list--linked list, fast and slow pointer to find the middle, merge sort

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.