链接
题目描述
思路
可以用循环或者递归的方式处理合并两个有序链表
对于合并K个有序链表,可以采用分治的思想
如果链表数组中,左半部分合并好了,右半部分合并好了,我们只需合并两个有序链表即可完成任务
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null || lists.length == 0){
return null;
}
if(lists.length == 1){
return lists[0];
}
int mid = lists.length/2;
ListNode[] l1 = new ListNode[mid];
ListNode[] l2 = new ListNode[lists.length-mid];
for(int i = 0; i < mid ;i++){
l1[i] = lists[i];
}
for(int i = 0; i < l2.length ;i++){
l2[i] = lists[mid+i];
}
return mergeTwoLists(mergeKLists(l1),mergeKLists(l2));
}
private ListNode mergeTwoLists(ListNode l1,ListNode l2){
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
if(l1.val < l2.val){
l1.next = mergeTwoLists(l1.next,l2);
return l1;
}else{
l2.next = mergeTwoLists(l1,l2.next);
return l2;
}
}
}
来源:CSDN
作者:十七十七跳跳糖
链接:https://blog.csdn.net/weixin_42469108/article/details/103651239