1、题目描述
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
2、算法分析
① 首先学会合并两个有序链表
具体请访问 https://blog.csdn.net/Sunshineoe/article/details/118669072
② 通过递归两两比较链表得出结果
3、代码实现
/**
* 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 result = null;
for(int i = 0;i < lists.length;i++){
// 两两比较,然后递归实现
result = mergeTwoLists(result,lists[i]);
}
return result;
}
// 合并两个链表
public ListNode mergeTwoLists(ListNode l1,ListNode l2){
// 创建一个新的链表存储结果集
ListNode dummy = new ListNode(0);
ListNode current = dummy;
// 合并两个链表
while(l1 != null && l2 != null){
if(l1.val < l2.val){
current.next = l1;
current = current.next;
l1 = l1.next;
}else{
current.next = l2;
current = current.next;
l2 = l2.next;
}
}
// 如果其中两个链表其中一个空,则输出的是另外一个链表
if(l1 == null){
current.next = l2;
}
if(l2 == null){
current.next = l1;
}
return dummy.next;
}
}