链表篇
/**
* 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 mergeTwoLists(ListNode list1,ListNode list2){
ListNode cur=new ListNode(0);
//哨兵节点
ListNode dummy=cur;
while(list1!=null&&list2!=null){
if(list1.val<list2.val){
cur.next=list1;
list1=list1.next;
}else{
cur.next=list2;
list2=list2.next;
}
cur=cur.next;
}
//拼接剩余链表
cur.next=list1!=null?list1:list2;
return dummy.next;
}
//合并所有升序链表
public ListNode mergeKLists(ListNode[] lists) {
int m=lists.length;
if(m==0){
return null;
}
if(m==1){
return lists[0];
}
//二分法,切成两半
int mid=m/2;
ListNode left=mergeKLists(java.util.Arrays.copyOfRange(lists,0,mid));
ListNode right=mergeKLists(java.util.Arrays.copyOfRange(lists,mid,m));
return mergeTwoLists(left,right);
}
}
标签:ListNode,val,int,list1,next,链表,升序,java From: https://blog.csdn.net/m0_73629042/article/details/142851325