链表排序

来源:互联网 发布:surface适合编程吗 编辑:程序博客网 时间:2024/06/05 00:57
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *getMiddle(ListNode *head)    {        ListNode *fast=head;        ListNode *slow=head;                while(fast->next!=NULL)        {            fast=fast->next;                        if(fast->next!=NULL)                fast=fast->next;            else                break;            slow=slow->next;        }        return slow;    }    ListNode *merge(ListNode *list1,ListNode *list2)    {        ListNode *newhead=new ListNode(0);        ListNode *head=newhead;                while(list1!=NULL&&list2!=NULL)        {            if(list1->val<list2->val)            {                newhead->next=list1;                list1=list1->next;            }            else            {                newhead->next=list2;                list2=list2->next;            }            newhead=newhead->next;        }        if(list1==NULL)            newhead->next=list2;        else            newhead->next=list1;                    return head->next;    }    ListNode *sortList(ListNode *head) {        if(head==NULL||head->next==NULL)            return head;        ListNode *mid=getMiddle(head);        ListNode *head2=mid->next;        mid->next=NULL;        return merge(sortList(head),sortList(head2));    }};



使用头结点归并的方法可大幅度降低逻辑上的复杂度

0 0
原创粉丝点击