题解 | #单链表的排序#

单链表的排序

http://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08

 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    ListNode* merge(ListNode* head1,ListNode* head2){
        if(!head1)
            return head2;
        if(!head2)
            return head1;
        ListNode* cur;
        ListNode* ans;
        cur=new ListNode(-1);
        ans=cur;
        while(head1&&head2){
            if(head1->val<=head2->val){
                cur->next=head1;
                head1=head1->next;
            }
            else {
                cur->next=head2;
                head2=head2->next;
            }
            cur=cur->next;
        }
        cur->next=head1?head1:head2;
        return ans->next;
    }
    ListNode* sortInList(ListNode* head) {
        // write code here
        if(!head||!head->next)
            return head;
        ListNode *left,*mid,*right;
        left=head;
        mid=head->next;
        right=head->next->next;
        while(right&&right->next){
            left=left->next;
            mid=mid->next;
            right=right->next->next;
        }
     //   return head;
        left->next=NULL;
        return merge(sortInList(head),sortInList(mid));
    }
};
全部评论

相关推荐

叁六玖:你看,最后不是让你加油,就是鼓励你,还祝福你求职顺利。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务