题解 | #合并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
        ListNode result = new ListNode(0);
        if (lists.size() == 0 || lists==null) {
            return null;
        }
        if (lists.size() < 2) {
            return lists.get(0);
        } 
        int begin =0;
        int end =lists.size()-1;
            while(begin<end){
                ListNode tem =lists.get((0));
                lists.set(0,compare(lists.get(0),lists.get(end)));
                end--;
            }
        
            return lists.get(0);
       
    }
    public ListNode compare(ListNode listnode1, ListNode listnode2) {
        if (listnode1 == null) return listnode2;
        if (listnode2 == null) return listnode1;
        if (listnode1.val < listnode2.val) {
            listnode1.next = compare(listnode1.next, listnode2);
            return listnode1;
        } else {
            listnode2.next = compare(listnode1, listnode2.next);
            return listnode2;
        }
    }
}

全部评论

相关推荐

我就是0offer糕手:北大不乱杀
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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