LeetCode Sort List

Source: Internet
Author: User

Sort a linked list in the time of O (nlogn .. It is obvious to use merge or quick sort.

The first time I knew that the original merger could also be written using a linked list, I was brushed down to three views ..... Use the speed pointer method to find the demarcation point.

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:ListNode *getMid(ListNode *head){ListNode *slow=head;ListNode *fast=head;while(fast->next!=NULL&&fast->next->next!=NULL){slow=slow->next;fast=fast->next;fast=fast->next;}return slow;}    ListNode *sortList(ListNode *head)     {    if(head==NULL||head->next==NULL)    {    return head;    }    ListNode *mid=getMid(head);    ListNode *next=mid->next;    mid->next=NULL;    return mergeList(sortList(head),sortList(next));    }    ListNode *mergeList(ListNode *a,ListNode *b)    {    ListNode *tmphead=new ListNode(-1);    ListNode *cur=tmphead;    while(a&&b)    {    if(a->val<=b->val)    {    cur->next=a;    a=a->next;    }    else    {    cur->next=b;    b=b->next;    }    cur=cur->next;    }    cur->next=NULL;    cur->next= a==NULL?b:a;    cur=tmphead->next;    delete tmphead;    return cur;    }};


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.