class Solution {
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
return cutList(lists, 0, lists.length - 1);
}
//先将列表切割成两个链表一组
private ListNode cutList(ListNode[] lists, int left, int right) {
//当被切割成一个时,回退到上一层递归,进行return mergeTwoLists(l1, l2)
if (left == right) return lists[left];
int mid = left + (right - left) / 2;
ListNode l1 = cutList(lists, left, mid);
ListNode l2 = cutList(lists, mid + 1, right);
return mergeTwoLists(l1, 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(l2.next, l1);
return l2;
}
}
}
leetcode23. 合并K个排序链表
最新推荐文章于 2024-06-21 10:00:00 发布