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

合并k个已排序的链表

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

    public ListNode mergeKLists (ArrayList<ListNode> lists) {
        // write code here
        if (lists == null || lists.isEmpty()) return null;
    
        Iterator<ListNode> it = lists.iterator();
        ListNode res = it.next();
        while (it.hasNext()) res = merge(res, it.next());

        return res;
    }

    private ListNode merge(ListNode a, ListNode b) {
        if (a == null) return b; 
        if (b == null) return a; 

        if(a.val <= b.val) {
            a.next = merge(a.next, b);
            return a;
        } else {
            b.next = merge(b.next, a);
            return b;
        }
    }

全部评论

相关推荐

点赞 评论 收藏
转发
特斯联 后端开发 300 + 450餐补
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务