Lc23_合并K个排序链表

//合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 
//
// 示例: 
//
// 输入:
//[
//  1->4->5,
//  1->3->4,
//  2->6
//]
//输出: 1->1->2->3->4->4->5->6 
// Related Topics 堆 链表 分治算法

package leetcode.editor.cn;

import com.example.demo.ListNode;

//Java:合并K个排序链表
public class P23MergeKSortedLists{
    public static void main(String[] args) {
        Solution solution = new P23MergeKSortedLists().new Solution();
        // TO TEST
    }
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode res = null;
        for (int i = 0; i < lists.length; i++) {
            res =  merge(res,lists[i]);
        }
        return res;

    }

    //依次合并链表
    private ListNode merge(ListNode l1, ListNode l2){
        if(l1==null){
            return l2;
        }

        if(l2==null){
            return l1;
        }

        if(l1.val<l2.val){
           l1.next = merge(l1.next,l2);
           return l1;
        }else{
          l2.next =merge(l1,l2.next);
          return l2;
        }
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}

posted @ 2020-07-15 15:21  小傻孩丶儿  阅读(111)  评论(0编辑  收藏  举报