题解 | #合并k个已排序的链表#

合并k个已排序的链表

https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

import java.util.*;
/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * @param lists ListNode类ArrayList 
     * @return ListNode类
     */
  //努力改善自己的代码缺陷,如有代码/规范问题,烦请不吝赐教。
    public ListNode mergeKLists (ArrayList<ListNode> lists) {
        // write code here
        int size=lists.size();
        if(size==0){
            return null;
        }
        if(size==1){
            return lists.get(0);
        }
        ArrayList<ListNode> list=new ArrayList();
        for(int i=0,j=size-1;i<=j;i++,j--){
            if(i!=j){
                list.add(mergeTwoLists(lists.get(i),lists.get(j)));
            }else{
                list.add(lists.get(i));
            }
        }
        return mergeKLists(list);
    }
    private static ListNode mergeTwoLists(ListNode h1,ListNode h2){
        if(h1==null){
            return h2;
        }
        if(h2==null){
            return h1;
        }
        ListNode p=new ListNode(0);
        ListNode q=p;
        while(h1!=null && h2!=null){
            if(h1.val<=h2.val){
                p.next=h1;
                h1=h1.next;
            }else{
                p.next=h2;
                h2=h2.next;
            }
            p=p.next;
        }
        if(h1!=null){
            p.next=h1;
        }else{
            p.next=h2;
        }
        p=q.next;
        q.next=null;
        return p;
    }
}

全部评论

相关推荐

10-01 09:50
门头沟学院 Java
肖先生~:这个人真的很好,点赞
点赞 评论 收藏
分享
09-24 18:30
已编辑
长春工业大学 产品经理
小肥罗:HR就是好人的缩写哈哈哈哈
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务