合并K个升序链表

题目

给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

代码

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        
        ListNode head = null;
        for(int i=0;i<lists.length;i++) {
            head = merge2Lists(head,lists[i]);
        }
       return head;
    }

    //合并2个链表
    public ListNode merge2Lists(ListNode head,ListNode list) {
        
        if (head == null || list == null) {        
            return head != null ? head : list;
        } else {
            ListNode h = null;
            ListNode cur = null;
            while (head != null && list != null) {
                if (head.val <= list.val) {
                    if(h == null) {
                        h = head;
                        cur = h;                      
                    } else {
                        cur.next = head;
                        cur = cur.next;
                    }
                    head = head.next;             
                } else {
                    if (h == null) {
                        h = list;
                        cur = h;                      
                    } else {
                        cur.next = list;
                        cur = cur.next;
                    }
                    list = list.next;
                }
                
            }
            cur.next = (head != null ? head : list);
            return h;
        }

    }
}

说明:提交的使用的测试用例,是[[2],[],[-1]]。在最开始的时候提交报错,因为没有考虑到中间的链表为空的情况。
写的如下:

 if (head == null) {
    head = list;
     return head;
 }

正确做法是:

 if (head == null || list == null) {        
     return head != null ? head : list;
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值