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);
        }
    }
  • 相关阅读:
    剑指offer 面试26题
    剑指offer 面试25题
    剑指offer 面试24题
    剑指offer 面试23题
    剑指offer 面试22题
    剑指offer 面试19题
    剑指offer 面试20题
    剑指offer 面试21题
    剑指offer 面试18题
    剑指offer 面试17题
  • 原文地址:https://www.cnblogs.com/googlemeoften/p/5818241.html
Copyright © 2011-2022 走看看