BM12 单链表的排序 C++

BM12 单链表的排序

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    public ListNode sortInList (ListNode head) 
    {
        // write code here
        // 开始分割
        return cut(head);
        // 开始合并
    }
    
    public ListNode cut(ListNode head)
    {
        //设置快慢指针
        if(head.next == null)
        {
            return head;
        }
        ListNode fast = head.next;
        ListNode low = head;
        //开始遍历
        while(fast != null && fast.next != null)
        {
            fast = fast.next.next;
            low = low.next;
        }
        //low即为中间的结点
        ListNode head2  = low.next;
        low.next = null;
        //现在有两个头结点即为 head和head2
        return merge(cut(head),cut(head2));
    }
    
    public ListNode merge(ListNode head1,ListNode head2)
    {
        ListNode dummyNode = new ListNode(-1);
        ListNode head = dummyNode;
        while(head1 != null && head2 != null)
        {
            ListNode cur = new ListNode(-1);
            if(head1.val <= head2.val)
            {
                cur = head1;
                head1 = head1.next;
            }
            else{
                cur = head2;
                head2 = head2.next;
            }
            cur.next = null;
            head.next = cur;
            head = head.next;
        }
        if(head1 != null)
        {
            head.next = head1;
        }
        if(head2 != null)
        {
            head.next = head2;
        }
        return dummyNode.next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值