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);
    }
}
相关推荐
星星火柴9361 小时前
关于“双指针法“的总结
数据结构·c++·笔记·学习·算法
艾莉丝努力练剑2 小时前
【洛谷刷题】用C语言和C++做一些入门题,练习洛谷IDE模式:分支机构(一)
c语言·开发语言·数据结构·c++·学习·算法
闪电麦坤953 小时前
数据结构:迭代方法(Iteration)实现树的遍历
数据结构·二叉树·
C++、Java和Python的菜鸟3 小时前
第六章 统计初步
算法·机器学习·概率论
Cx330❀3 小时前
【数据结构初阶】--排序(五):计数排序,排序算法复杂度对比和稳定性分析
c语言·数据结构·经验分享·笔记·算法·排序算法
散1123 小时前
01数据结构-Prim算法
数据结构·算法·图论
起个昵称吧4 小时前
线程相关编程、线程间通信、互斥锁
linux·算法
阿巴~阿巴~4 小时前
深入解析C++ STL链表(List)模拟实现
开发语言·c++·链表·stl·list
..过云雨4 小时前
01.【数据结构-C语言】数据结构概念&算法效率(时间复杂度和空间复杂度)
c语言·数据结构·笔记·学习
myzzb4 小时前
基于uiautomation的自动化流程RPA开源开发演示
运维·python·学习·算法·自动化·rpa