题目:力扣https://leetcode-cn.com/problems/merge-k-sorted-lists/
/**
* 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 mergeKLists(ListNode[] lists) {
if(lists.length<1) return null;
ListNode ans = lists[0];
for(int i=1;i<lists.length;i++){
ans = combine(ans,lists[i]);
}
return ans;
}
private ListNode combine(ListNode a,ListNode b){
ListNode res = new ListNode(0);
ListNode cur = res;
while(a!=null && b!=null){
if(a.val<b.val){
cur.next = a;
a = a.next;
}else{
cur.next = b;
b = b.next;
}
cur = cur.next;
}
if(a==null){
cur.next = b;
}else{
cur.next = a;
}
return res.next;
}
}
思路:这道题我将其视为leetcode21.合并两个有序链表的扩展题。这样的好处就是可以偷懒,不用重新想思路,之前是合并两个有序链表,而现在不过是合并多个链表。而坏处就是,这样偷懒的方法效率并不高。但不管怎么说,能AC就算一种方法吧,凑合着用着,以后再写其他解法。
1.写一个两有序链表合并的方法。这里完全就是故技重施,不再详细赘述。详情点击——>leetcode21.合并两个有序链表
private ListNode combine(ListNode a,ListNode b){
ListNode res = new ListNode(0);
ListNode cur = res;
while(a!=null && b!=null){
if(a.val<b.val){
cur.next = a;
a = a.next;
}else{
cur.next = b;
b = b.next;
}
cur = cur.next;
}
if(a==null){
cur.next = b;
}else{
cur.next = a;
}
return res.next;
}
2.增强代码健壮性(其实就是过滤掉“流氓”例子哈哈哈)
if(lists.length<1) return null;
3.新建一条链,让其先指向lists[0],然后利用循环让其两两合并,合并到最后便是题目所求的答案,返回即可。
ListNode ans = lists[0];
for(int i=1;i<lists.length;i++){
ans = combine(ans,lists[i]);
}
return ans;