题目描述
题意解析
给定k个升序链表,将其合并为一个升序链表。
思路分析
一开始的思路是想着怎么一口气之间合并k个,后来感觉空间时间开销较大,之后参考了下官方给出的题解,每次合并两个链表。
合并两个链表:假设有链表A和链表B,首先判断两个链表当前节点值的大小关系,将较小值节点设置为新链表C的下一个节点,不断循环进行此操作,直至A和B其中一个被遍历完。若剩下的一个链表没有被遍历完,则说明剩下的值都是大于新链表C中的值,直接将其接到C后面即可。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode a, ListNode b){
if(a == null || b == null) return a!=null?a:b;
ListNode head = new ListNode();
ListNode cur = head;
ListNode cura = a, curb = b;
while(cura != null && curb != null){
if(cura.val < curb.val){
cur.next = cura;
cura = cura.next;
}else{
cur.next = curb;
curb = curb.next;
}
cur = cur.next;
}
if(cura != null) cur.next = cura;
if(curb != null) cur.next = curb;
return head.next;
}
public ListNode mergeKLists(ListNode[] lists) {
ListNode ans = null;
int k = lists.length;
for(int i=0;i<k;i++){
ans = mergeTwoLists(ans, lists[i]);
}
return ans;
}
}