LeetCode:Sort a linked list in O(n log n) time using constant space complexity.(链表排序)

题目描述:

链表排序,空间复杂度要求O(nlogn)。

时间复杂度为O(nlogn)的排序方式为归并排序。

先把链表分成小链表,小到只有一个元素,这样就编程有序的了,然后就是有序链表的合并,归并的原理就是这样的,关键是怎么编程实现,这里用到两个关键的方法:

1、将链表分成小链表的方法。这个方法要掌握,在链表中和很多地方要用到。一般都是采用两个指针一个快指针一个满指针,快指针每次走两步,慢指针每次走一步,这样最后的路程就是快指针是慢指针的两倍,所以快指针走到链表结尾的时候,慢指针正好走到链表的中间。这就将链表分成了小链表。

2、有序链表的合并。有序链表的合并也有许多地方要用到,这个的实现原理就是将两个链表按顺序逐渐插入到一个新的链表中。

下面的是编程实现:

public class Solution {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next==null) {
            return head;
        }
        ListNode right = getMid(head);
        ListNode rightNext = right.next;
        right.next = null;//这一步很重要,如果没有,就分不开了。
        return merget(sortList(head), sortList(rightNext));
    }
    //两个有序链表和合并的方法
    public ListNode merget(ListNode oneL, ListNode twoL) {
        if (oneL == null) {
            return twoL;
        } else if (twoL == null) {
            return oneL;
        }
        ListNode one=oneL;
        ListNode two=twoL;
        ListNode newList =new ListNode(0);
        ListNode tempNode = newList;
        while (one != null && two != null) {
            if (one.val <= two.val) {
                tempNode.next = one;
                one = one.next;
            } else {
                tempNode.next = two;
                two = two.next;
            }
            tempNode=tempNode.next;
        }
        if (one != null) {
            tempNode.next = one;
        }
        if (two != null) {
            tempNode.next = two;
        }
        return newList.next;
    }
    //找到中间元素的方法,从而将链表分开
    private ListNode getMid(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode slow = head, quick = head;
        while (quick.next != null && quick.next.next != null) {
            slow = slow.next;
            quick = quick.next.next;
        }
        return slow;
    }
}

欢迎批评指正,谢谢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值