0
点赞
收藏
分享

微信扫一扫

leetcode(23)合并K个升序链表

爱薇Ivy趣闻 2022-04-17 阅读 49
算法

给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        int n = lists.length;
        ListNode res = null;
        for(int i=0; i<n; i++){
            res = mergeTwoLists(res,lists[i]);
        }
        return res;
    }

    public ListNode mergeTwoLists(ListNode a, ListNode b){
        if(a==null || b==null){
            return a!=null?a:b;
        }
        ListNode head = new ListNode(0);
        ListNode cur = head, i = a, j = b;
        while(i != null && j != null){
            if(i.val > j.val){
                cur.next = j;
                j = j.next;
                
            }else{
                cur.next = i;
                i = i.next;
            }
            cur = cur.next;
        }
        cur.next = i==null ? j:i;
        return head.next;

    }
}
举报

相关推荐

0 条评论