LeetCode Sort List

来源:互联网 发布:淘宝库存同步软件 编辑:程序博客网 时间:2024/05/22 16:50

在 O(nlogn)的时间内对一个链表进行排序。。明显是要用归并或者快排

第一次知道说原来归并也可以用链表来写,被刷了下三观。。。。。用快慢指针的方法找分界点。

/** * 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;    }};


0 0