在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。归并排序,Java实现

35 篇文章 0 订阅
7 篇文章 0 订阅
/**
 * 在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
 */
public class SortList {
    //排序链表
    public static ListNode sortList(ListNode list){
        if(list == null || list.next == null){
            return list;
        }
        //获取中间节点
        ListNode mid = getMiddleNode(list);
        //保留链表后半段的头结点
        ListNode after = mid.next;
        //截断链表
        mid.next = null;
        ListNode left = sortList(list);
        ListNode right = sortList(after);
        ListNode result = mergeTwoList(left, right);
        return result;
    }
    //合并两个有序链表
    public static ListNode mergeTwoList(ListNode l1, ListNode l2){
        ListNode current = new ListNode(0);
        ListNode result = current;
        while(l1 != null && l2 != null){
            if(l1.val > l2.val){
                current.next = l2;
                l2 = l2.next;

            }else{
                current.next = l1;
                l1 = l1.next;
            }
            current = current.next;
        }
        if(l1 == null){
            current.next = l2;
        }else{
            current.next = l1;
        }
        return result.next;
    }

    //获取链表的中间节点
    public static ListNode getMiddleNode(ListNode head){
        //如果只有一个节点,就直接返回
        if(head == null || head.next == null){
            return head;
        }
        ListNode slow = head;
        ListNode fast = head;
        while(fast != null && fast.next != null){
            //一次移动一个节点
            slow = slow.next;
            //一次移动两个节点
            fast = fast.next.next;
        }
        return slow;
    }

    public static void main(String[] args){
        ListNode list = new ListNode(-1);
        ListNode node1 = new ListNode(9);
        ListNode node2 = new ListNode(1);
        ListNode node3 = new ListNode(8);
        ListNode node4 = new ListNode(0);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(3);
        ListNode node7 = new ListNode(7);
        list.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = node7;

        ListNode listNode = sortList(list);
        while (listNode != null){
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }
}


class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值