148. Sort List

一、题目

  1、审题

  

  2、分析

    将一个链表节点进行排序,时间复杂度为 NLogN, 且使用常数的空间复杂度。

二、解答

  1、思路:

      采用归并排序的思想。

      ①、将链表进行切割

      ②、将切割的链表进行排序

      ③、合并切割的链表。

    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        
        ListNode prev = null;
        ListNode slow = head;
        ListNode fast = head;
        
        // step 1. cut the list to two halves
        while(fast != null && fast.next != null) {
            prev = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        
        prev.next = null;
        
        // step 2. sort each half
        ListNode l1 = sortList(head);
        ListNode l2 = sortList(slow);
        
        // step 3. merge l1 and l2
        return merge(l1, l2);
    }
    
    private ListNode merge(ListNode l1, ListNode l2) {
        
        ListNode lNode = new ListNode(0);
        ListNode pNode = lNode;
        
        while(l1 != null && l2 != null) {
            if(l1.val < l2.val) {
                pNode.next = l1;
                l1 = l1.next;
            }
            else {
                pNode.next = l2;
                l2 = l2.next;
            }
            pNode = pNode.next;
        }
        
        if(l1 != null)
            pNode.next = l1;
        if(l2 != null)
            pNode.next = l2;
        
        return lNode.next;
    }
原文地址:https://www.cnblogs.com/skillking/p/9779948.html