Combinar K listas enlazadas ascendentes

Combinar K listas enlazadas ascendentes

class Solution {
    
    
    public ListNode mergeKLists(ListNode[] lists) {
    
    
        return merge(lists, 0, lists.length - 1);
    }

    public ListNode merge(ListNode[] lists, int l, int r) {
    
    
        if (l == r) {
    
    
            return lists[l];
        }
        if (l > r) {
    
    
            return null;
        }
        int mid = (l + r) >> 1;
        return mergeTwoLists(merge(lists, l, mid), merge(lists, mid + 1, r));
    }

    public ListNode mergeTwoLists(ListNode a, ListNode b) {
    
    
        if (a == null || b == null) {
    
    
            return a != null ? a : b;
        }
        ListNode head = new ListNode(0);
        ListNode tail = head, aPtr = a, bPtr = b;
        while (aPtr != null && bPtr != null) {
    
    
            if (aPtr.val < bPtr.val) {
    
    
                tail.next = aPtr;
                aPtr = aPtr.next;
            } else {
    
    
                tail.next = bPtr;
                bPtr = bPtr.next;
            }
            tail = tail.next;
        }
        tail.next = (aPtr != null ? aPtr : bPtr);
        return head.next;
    }
}

Supongo que te gusta

Origin blog.csdn.net/xiaomagezuishuai/article/details/114197232
Recomendado
Clasificación