首页 > 编程语言 > 详细

链表排序

时间:2015-02-02 21:35:22      阅读:166      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!