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);
        }
    }
  • 相关阅读:
    131. Palindrome Partitioning
    130. Surrounded Regions
    129. Sum Root to Leaf Numbers
    128. Longest Consecutive Sequence
    125. Valid Palindrome
    124. Binary Tree Maximum Path Sum
    122. Best Time to Buy and Sell Stock II
    121. Best Time to Buy and Sell Stock
    120. Triangle
    119. Pascal's Triangle II
  • 原文地址:https://www.cnblogs.com/googlemeoften/p/5818241.html
Copyright © 2011-2022 走看看