给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
int n = lists.length;
ListNode res = null;
for(int i=0; i<n; i++){
res = mergeTwoLists(res,lists[i]);
}
return res;
}
public ListNode mergeTwoLists(ListNode a, ListNode b){
if(a==null || b==null){
return a!=null?a:b;
}
ListNode head = new ListNode(0);
ListNode cur = head, i = a, j = b;
while(i != null && j != null){
if(i.val > j.val){
cur.next = j;
j = j.next;
}else{
cur.next = i;
i = i.next;
}
cur = cur.next;
}
cur.next = i==null ? j:i;
return head.next;
}
}