码迷,mamicode.com
首页 > 编程语言 > 详细

链表排序

时间:2015-02-02 21:38:39      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:链表   归并排序   

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



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

链表排序

标签:链表   归并排序   

原文地址:http://blog.csdn.net/u013011841/article/details/43413343

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!