题解 | 合并k个已排序的链表

合并k个已排序的链表

https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param lists ListNode类ArrayList 
     * @return ListNode类
     */
    public ListNode mergeKLists (ArrayList<ListNode> lists) {
        if (lists == null) {
            return null;
        }
        
        lists.removeIf((n) -> null == n);

        if (lists.isEmpty()) {
            return null;
        }

        ListNode head = lists.get(0);
        for (int i = 1; i < lists.size(); i++) {
            // 这里合并将链表转数组后再转链表
            // 目的是创建一个新的链表
            head = merge(head, lists.get(i));
        }

        return head;
    }

    // 链表合并且升序排序
    public ListNode merge(ListNode l1, ListNode l2) {
        // if (null == l1) {
        //     return l2;
        // } else if (null == l2) {
        //     return l1;
        // } else if (l1.val < l2.val) {
        //     l1.next = merge(l1.next, l2);
        //     return l1;
        // } else {
        //     l1.next = merge(l1, l2.next);
        //     return l2;
        // }
        // 转数组, 深Copy
        int t1 = 0;
        ListNode nt1 = new ListNode(l1.val);
        nt1.next = l1.next;
        while (nt1 != null) {
            t1++;
            nt1 = nt1.next;
        }

        int t2 = 0;
        ListNode nt2 = new ListNode(l2.val);
        nt2.next = l2.next;
        while (nt2 != null) {
            t2++;
            nt2 = nt2.next;
        }

        int[] nums = new int[t1 + t2];
        int index = 0;
        while (null != l1) {
            nums[index++] = l1.val;
            l1 = l1.next;
        }
        while (null != l2) {
            nums[index++] = l2.val;
            l2 = l2.next;
        }

        Arrays.sort(nums);

        // 拼接链表
        ListNode dummy = new ListNode(-1);
        ListNode head = dummy;
        for (int num : nums) {
            ListNode node = new ListNode(num);
            head.next = node;
            head = head.next;
        }

        return dummy.next;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务