[Linked list] Merge k sorted linked lists (merge sort)

 

import java.util.*;
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ArrayList<ListNode> lists) {
        return mergeList(lists,0,lists.size()-1);
    }
    public ListNode mergeList(ArrayList<ListNode> lists,int L,int R){
        if(L==R){
            return lists.get(L);
        }
        if(L>R)return null;
        int mid=L+((R-L)>>1);
        return merge(mergeList(lists,L,mid),mergeList(lists,mid+1,R));
    }
    public ListNode merge(ListNode l1,ListNode l2){
        if(l1==null||l2==null){
            return l1==null?l2:l1;
        }
        ListNode dummyNode=new ListNode(-1);
        ListNode cur=dummyNode;
        while(l1!=null&&l2!=null){
            if(l1.val<l2.val){
                cur.next=l1;
                l1=l1.next;
            }else{
                cur.next=l2;
                l2=l2.next;
            }
            cur=cur.next;
        }
        cur.next=(l1==null?l2:l1);
        return dummyNode.next;
    }
}

 

おすすめ

転載: blog.csdn.net/m0_52043808/article/details/124264454