基本思路:想要合并多个升序的链表,前提是需要会合并两个升序排列的链表。具体的方法在之前的博文中有提及合并两个有序的链表
大概的思路和合并两个有序数组基本相同,就是在链表的最开始确定两个指针,根据指针来确定哪个链表的元素更小一点,将小的哪个链表移入到合并的链表中并后移以为,然后继续比较最前面的指针,重复以上的步骤直到一个链表为空,说明另外一个链表中存在的数都是最大的数,只需要将他们连接到合并链表的后面就完成了。
合并多个链表就是循环合并两个链表的过程,我们合并第一个第二个链表生成一个新的链表,然后用这个新生成的链表去合并第三个链表以此类推。。。。代码如下:
/**
* 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) {
ListNode head = null;
if(lists == null || lists.length == 0){
return head;
}
head = lists[0];
for(int i = 0;i < lists.length - 1;i++){
head = mergeTwoLists(head,lists[i+1]);
}
return head;
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
ListNode head = null;
ListNode next = null;
while(l1 != null && l2 != null){
if(l1.val > l2.val){
if(head == null){
head = l2;
next = l2;
}else{
next.next = l2;
next = next.next;
}
l2 = l2.next;
}else{
if(head == null){
head = l1;
next = l1;
}else{
next.next = l1;
next = next.next;
}
l1 = l1.next;
}
}
if(l1 == null){
next.next = l2;
}
if(l2 == null){
next.next = l1;
}
return head;
}
}