Leetcode: Sort List (Java)

本文介绍了一种在单链表上实现归并排序的方法,详细解释了如何将链表一分为二并进行排序,最后通过合并操作得到有序链表。

要求时间复杂度是O(nlogn),空间是constant space。想一下,平均时间复杂度满足这个的只有快速排序,归并排序和堆排序。因为是单链表,排除快速排序。堆需要建树,我也排除。因而我选择归并排序。
1. 首先要讲链表在中间切开,为了在一次循环中找到第二个子链表的head,我设置了count用以搜寻表尾,secondhead用以指向第二个子链表的头,beforesecond用以指向secondhead的前一个节点,用来切开原链表。count每前移两次,secondhead才前移一次,beforehead才前移一次,如此,可对半切开链表。
2. 合并过程比较简单,不断将next指针指向值较小的子链表即可。

贴代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode sortList(ListNode head) {
        if (head==null) return null;
        if (head.next==null) return head;
        if (head.next.next==null) {
            if (head.val <= head.next.val) return head;
            else {
                int val = head.val;
                head.val = head.next.val;
                head.next.val = val;
                return head;
            }
        }

        ListNode secondhead = head.next;
        ListNode beforesecond = head;
        ListNode count = head.next.next.next;
        while(count!=null) {
            beforesecond = secondhead;
            secondhead = secondhead.next;
            if (count.next==null) break;
            else count = count.next.next;
        }
        beforesecond.next = null;

        head = sortList(head);
        secondhead = sortList(secondhead);
        ListNode newhead = new ListNode(0);
        ListNode node = newhead;
        while (head!=null && secondhead!=null) {
            if (head.val <= secondhead.val) {
                node.next = head;
                head = head.next;
                node = node.next;
            }
            else {
                node.next = secondhead;
                secondhead = secondhead.next;
                node = node.next;
            }
        }

        if (head!=null) {
            node.next = head;
        }
        else node.next = secondhead;
        newhead = newhead.next;
        return newhead;
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值