Sort a linked list in O(n log n) time using constant space complexity.

思路:

因为题目要求复杂度为O(nlogn),故可以考虑归并排序的思想。

归并排序的一般步骤为:

1)将待排序数组(链表)取中点并一分为二;

2)递归地对左半部分进行归并排序;

3)递归地对右半部分进行归并排序;

4)将两个半部分进行合并(merge),得到结果。

 

所以对应此题目,可以划分为三个小问题:

1)找到链表中点 (快慢指针思路,快指针一次走两步,慢指针一次走一步,快指针在链表末尾时,慢指针恰好在链表中点);

2)写出merge函数,即如何合并链表。 (见merge-two-sorted-lists 一题解析)

3)写出mergesort函数,实现上述步骤

代码:

/**
 * 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 l = head;
        ListNode r = head;
 
        while (r.next != null && r.next.next != null) {
            l = l.next;
            r = r.next.next;
        }
 
        //排序右半部分
        r = sortList(l.next);
        l.next = null;
        l = sortList(head);
 
        ListNode res = mergeList(l, r);
        return res;
    }
     
    private static ListNode mergeList(ListNode l, ListNode r) {
        ListNode p = l;
        ListNode q = r;
        ListNode fakehead = new ListNode(0);
        ListNode head = fakehead;
 
        while (p != null && q != null) {
            if (p.val < q.val) {
                fakehead.next = p;
                fakehead = fakehead.next;
                p = p.next;
            } else {
                fakehead.next = q;
                fakehead = fakehead.next;
                q = q.next;
            }
        }
        if (p==null){
            fakehead.next=q;
        }else {
            fakehead.next=p;
        }
 
 
        return head.next;
 
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值