23. 合并 K 个升序链表

给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。

/**
 * 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 {
    /*public static void main(String[] args) {
        ListNode[] lists = new ListNode[3];
        lists[0] = new ListNode(1);
        lists[0].add(4);
        lists[0].add(5);
        lists[1] = new ListNode(1);
        lists[1].add(3);
        lists[1].add(4);
        lists[2] = new ListNode(2);
        lists[2].add(2);
        lists[2].add(6);

        ListNode res = mergeKLists(lists);
    }*/

    public static ListNode mergeKLists(ListNode[] lists) {
        ListNode headNode = new ListNode();
        ListNode curNode = headNode;
        int len = lists.length;
        if (len == 0) {
            return null;
        }
        if (!len1(lists)) {
            return null;
        }
        for (int i = 0; i < len; i = (i + 1) % len) {
            if (!len1(lists)) {
                return headNode.next;
            }
            int index = min1(lists);
            ListNode newNode = new ListNode();
            newNode.val = lists[index].val;
            lists[index] = lists[index].next;
            curNode.next = newNode;
            curNode = newNode;
        }
        return headNode.next;
    }

    private static int min1(ListNode[] lists) {
        int i = 0;
        while (lists[i] == null) {
            i++;
        }
        for (int j = i + 1; j < lists.length; j++) {
            while (j < lists.length && lists[j] == null) {
                j++;
            }
            if (j < lists.length && lists[j].val < lists[i].val) {
                i = j;
            }
        }
        return i;
    }

    private static boolean len1(ListNode[] lists) {
        for (int i = 0; i < lists.length; i++) {
            if (lists[i] != null) {
                return true;
            }
        }
        return false;
    }
}

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