BM5 合并k个已排序的链表

目录

题目链接

题目​编辑

解题思路

代码


题目链接

合并k个已排序的链表_牛客题霸_牛客网

题目

解题思路

利用分治的思想,将一分成二,二分成四,最后划分成两两结合即可

代码
java 复制代码
import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    public ListNode Merge(ListNode pHead1,ListNode pHead2){
        if(pHead1==null){
            return pHead2;
        }
        if(pHead2==null){
            return pHead1;
        }
        ListNode dummyNode =new ListNode(0);
        ListNode cur=dummyNode;
        while(pHead1!=null&&pHead2!=null){
            if(pHead2.val<pHead1.val){
                cur.next=pHead2;
                pHead2=pHead2.next;
            }else{
                cur.next=pHead1;
                pHead1=pHead1.next;
            }
            cur=cur.next;
        }
        while(pHead1!=null){
            cur.next=pHead1;
            pHead1=pHead1.next;
            cur=cur.next;
        }
        while(pHead2!=null){
            cur.next=pHead2;
            pHead2=pHead2.next;
            cur=cur.next;
        }
        return dummyNode.next;
    }
    public ListNode divide(ArrayList<ListNode> lists,int left,int right){
        if(left>right){
            return null;
        }
        if(left==right){
            return lists.get(left);
        }
        int mid=(left+right)/2;
        return Merge(divide(lists,left,mid),divide(lists,mid+1,right));
    }
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param lists ListNode类ArrayList 
     * @return ListNode类
     */
    public ListNode mergeKLists (ArrayList<ListNode> lists) {
        // write code here
        return divide(lists,0,lists.size()-1);
    }
}
相关推荐
向哆哆19 小时前
画栈 · 跨端画师接稿平台:基于 Flutter × OpenHarmony 的整体设计与数据结构解析
数据结构·flutter·开源·鸿蒙·openharmony·开源鸿蒙
helloworldandy19 小时前
高性能图像处理库
开发语言·c++·算法
2401_8365631819 小时前
C++中的枚举类高级用法
开发语言·c++·算法
bantinghy19 小时前
Nginx基础加权轮询负载均衡算法
服务器·算法·nginx·负载均衡
chao18984419 小时前
矢量拟合算法在网络参数有理式拟合中的应用
开发语言·算法
代码无bug抓狂人19 小时前
动态规划(附带入门例题)
c语言·算法·动态规划
weixin_4454023020 小时前
C++中的命令模式变体
开发语言·c++·算法
季明洵20 小时前
C语言实现顺序表
数据结构·算法·c·顺序表
Hgfdsaqwr20 小时前
实时控制系统优化
开发语言·c++·算法
2301_8213696120 小时前
嵌入式实时C++编程
开发语言·c++·算法