码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_num148_Sort list

时间:2015-03-30 21:15:46      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   排序算法   

链表的归并排序

特别注意取中值函数的书写

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
public:
    ListNode *sortList(ListNode *head) {
        if(!head||!head->next)
            return head;
        ListNode *mid=GetMid(head);
        ListNode *midnext=mid->next;
        mid->next=NULL;
        ListNode *lefthead=sortList(head);
        ListNode *righthead=sortList(midnext);
        return Merge(lefthead,righthead);
        
    }
    ListNode *GetMid(ListNode *head){
        if(!head||!head->next)
            return head;
        ListNode *pNode1=head->next;//0,1,2,3 middle 1
        ListNode *pNode2=head;
        while(pNode1&&pNode1->next){// if pNode1==NULL
            pNode1=pNode1->next->next;
            pNode2=pNode2->next;
        }
        return pNode2;
    }
    ListNode *Merge(ListNode *lefthead,ListNode*righthead){
        ListNode *runner= new ListNode(10000);
        ListNode *head=lefthead->val<righthead->val?lefthead:righthead;
        while(lefthead&&righthead){
            if(lefthead->val<righthead->val){
                runner->next=lefthead;
                lefthead=lefthead->next;
                runner=runner->next;
            }
            else{
                runner->next=righthead;
                righthead=righthead->next;
                runner=runner->next;
            }
        }
        if(lefthead)
            runner->next=lefthead;
        else if(righthead)
            runner->next=righthead;
        return head;
    }
};


leetcode_num148_Sort list

标签:c++   leetcode   排序算法   

原文地址:http://blog.csdn.net/eliza1130/article/details/44756069

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