力扣 148. 排序链表

链表不难但是节点的分离连接还是比较复杂的,,
题目要求 nlogn的时间复杂度,所以选择归并排序的方法,同时空间复杂度为 1
所以每次从原链表中分离出两个子链表,排完序再连回去,反复的分离连接再分离,需要思维清楚

自己的(9ms)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    ListNode merge(ListNode l1, ListNode l2) {
        ListNode ans = new ListNode();
        ListNode q = ans;
        while(l1 != null && l2 != null){
            if(l1.val < l2.val){
                q.next = l1;
                l1 = l1.next;;
            }
            else{
                q.next = l2;
                l2 = l2.next;
            }
            q = q.next;
        }
        if(l1 != null)
         q.next = l1;
        if(l2 != null)
         q.next = l2;
        return ans.next;
    }
    public ListNode sortList(ListNode head) {
        ListNode l = head;
        int length = 0;
        while(l != null){
            length ++;
            l = l.next;
        }
        for(int i = 1; i < length; i *= 2){
            l = new ListNode(0,head);
            int jud = 1;
            while(l.next != null){
                ListNode l1,l2;
                l1 = l.next;
                for(int j = 1; j < i && l1.next !=null;j ++){
                    l1 = l1.next;
                }
                if(l1.next == null)
                    break;
                l2 = l1.next;
                for(int j = 1; j < i && l2.next != null;j ++){
                    l2 = l2.next;
                }
                ListNode t = l;
                l = l2.next;
                l2.next = null;
                l2 = l1.next;
                l1.next = null;
                l1 = t.next;
                t.next = merge(l1,l2);
                if(jud == 1){
                    head = t.next;
                    jud = 0;
                }
                while(t.next != null) t = t.next;
                t.next = l;
                l = t ;
                
            }
        }
        return head;
    }
}

你可能感兴趣的:(leetcode,算法,数据结构)