单向链表归并排序 Java

单向链表归并排序 use Java

链表的关键在于递归的时候中间位置的确定,方法是:用两个指针p,f 遍历链表,p走一步而f走两步;当f走完的时候p走到链表的一半!

这让我烧绳子那道逻辑题。

代码如下

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode sortList(ListNode head) {
        
        if (head == null || head.next == null){
            return head;
        }
        
        ListNode p = head;
        ListNode f = head.next;
        while ( f.next !=null && f.next.next !=null ){//locate p at half of the ListNode
            p = p.next;
            f = f.next.next;
        }
        
        ListNode h2 = sortList(p.next);
        p.next = null;
        
        return merge( sortList (head) , h2 );
        
    }
    
    public ListNode merge(ListNode h1,ListNode h2){
        
        ListNode hn = new ListNode(-1);
        ListNode c = hn;
        
        while (h1 != null && h2 != null ){
            if (h1.val <= h2.val){
                c.next = h1;
                h1 = h1.next;
            }else {
                c.next = h2;
                h2 = h2.next;
            }
            c = c.next;
        }
        
        if(h1 == null){
            c.next = h2;
        }else{
            c.next = h1;
        }
        
        return hn.next;
        
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值