【LeetCode】Sort List

链表的排序,非常适合利用归并排序来实现,采用递归的方式比较容易理解。

寻找一个链表的中间节点,采用快慢指针的方式。


/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getMiddleNode (ListNode h1){
        if(h1 == null || h1.next == null) return h1;
        ListNode dummy = new ListNode(0);
        ListNode fast = dummy;
        ListNode low = dummy;
        dummy.next = h1;
        while(low != null && fast!=null && fast.next != null){
            low = low.next;
            fast = fast.next;
            if(fast ==null)break;
            fast = fast.next;
        }
        ListNode middle = low.next;
        low.next = null;
        return middle;
    }
    public ListNode mergeTwoSortedList(ListNode h1, ListNode h2){
        if(h1 == null) return h2;
        if(h2 == null )return h1;
        ListNode dummy = new ListNode(-1);
        ListNode p = dummy;
        while(h1 != null && h2 != null){
            if(h1.val <= h2.val){
                p.next = h1;
                h1 = h1.next;
                p = p.next;
            }
            else{
                p.next = h2;
                h2 = h2.next;
                p = p.next;
            }
            if(h1 == null){
                while(h2 != null){
                    p.next = h2;
                    h2 = h2.next;
                    p = p.next;
                }
            }
            if(h2 == null){
                while(h1 != null){
                    p.next = h1;
                    h1 = h1.next;
                    p = p.next;
                }
            }
        }
        return dummy.next;
    }
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode mid = getMiddleNode(head);
        return mergeTwoSortedList(sortList(head), sortList(mid));
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值