zoukankan      html  css  js  c++  java
  • LeetCode:链表排序

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

    public class Solution {
        public ListNode sortList(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
    
            ListNode midNode = findMid(head);
            ListNode right = midNode.next;
            midNode.next = null;
    
            ListNode left = sortList(head);
            right = sortList(right);
    
            return merge(left, right);
        }
    
        public ListNode findMid(ListNode head) {
            ListNode slow = head;
            ListNode fast = head.next;
    
            while (fast != null && fast.next != null) {
                slow = slow.next;
                fast = fast.next.next;
            }
    
            return slow;
        }
    
        public ListNode merge(ListNode head1, ListNode head2) {
            ListNode dummy = new ListNode(0);//为了方便cur的移动
            ListNode cur = dummy;
    
            while (head1 != null & head2 != null) {
                if (head1.val < head2.val) {
                    cur.next = head1;
                    head1 = head1.next;
                } else {
                    cur.next = head2;
                    head2 = head2.next;
                }
                cur = cur.next;
            }
    
            if (head1 != null) {
                cur.next = head1;
            }
            if (head2 != null) {
                cur.next = head2;
            }
            return dummy.next;
        }
    
        public static void main(String[] args) {
            ListNode head = new ListNode(1);
            head.next = new ListNode(2);
            Solution solution = new Solution();
            solution.sortList(head);
        }
    }
  • 相关阅读:
    ES8 Async 和 Await
    js中字节B转化成KB,MB,GB
    理解与使用JavaScript中的回调函数
    JavaScript与函数式编程
    Deno 意味着什么?
    call、apply、bind
    测量JavaScript函数的性能的简单方法及与其他方式对比
    promise
    SQL游标原理和使用方法
    SQL循环语句
  • 原文地址:https://www.cnblogs.com/googlemeoften/p/5818241.html
Copyright © 2011-2022 走看看