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

合并k个已排序的链表

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

import java.util.*;

public class Solution {
    public ListNode mergeKLists (ArrayList<ListNode> lists) {
        int ss = lists.size();
        if(ss==0)
            return null;
        else if(ss==1)
            return lists.get(0);
        else if(ss==2){
            return union(lists.get(0), lists.get(1));
        }else {
            ListNode ll = lists.remove(0);
            ll = union(ll, mergeKLists(lists));
            return ll;
        }
    }
    public ListNode union(ListNode first, ListNode second){
        ListNode current=null;
        ListNode un = null;
        if(first==null)
            return second;
        if(second==null)
            return first;
        while(first!=null && second!=null){
            if(first.val<second.val){
                if(un == null) {
                    un = current = first;
                }else {
                    current.next = first;
                    current = current.next;
                }
                first = first.next;
            }else{
                if(un == null) {
                    un = current = second;
                }else {
                    current.next = second;
                    current = current.next;
                }
                second = second.next;
            }
        }
        if(first==null)
            current.next=second;
        if(second==null)
            current.next=first;
        return un;
    }
}

全部评论

相关推荐

刷牛客的我很豁达:你是不是对算法有什么误解,你没手握两篇顶刊顶会,还想搞算法岗,有顶刊顶会在算法岗算才入门
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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