题目
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
代码
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;
}