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

合并k个已排序的链表

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

import java.util.*;
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ArrayList<ListNode> lists) {
        if (lists.size() == 0) {
            return null;
        }
        for (int i = 0; i < lists.size() - 1; i++) {
            ListNode left = lists.get(i);
            ListNode right = lists.get(i + 1);

            ListNode m = Merge(left, right);
            lists.add(m);
            i += 1;
        }

        return lists.get(lists.size() - 1);
    }


    public ListNode Merge(ListNode list1, ListNode list2) {

        if (list1 == null || list2 == null) {
            if (list1 != null) {
                return list1;
            }
            return list2;
        }

        ListNode head = new ListNode(-1 );
        ListNode p = head;
        while (list1 != null && list2 != null) {
            ListNode temp1Node, temp2Node;
            temp1Node = list1.next;
            temp2Node = list2.next;
            ListNode curNode = new ListNode(-1);

            if (list1.val < list2.val) {
                curNode.val = list1.val;
                curNode.next = head.next;
                head.next = curNode;
                head = head.next;
                list1 = temp1Node;
            } else {
                curNode.val = list2.val;
                curNode.next = head.next;
                head.next = curNode;
                head = head.next;
                list2 = temp2Node;
            }
        }
        if (list1 != null) {
            head.next = list1;
        }
        if (list2 != null) {
            head.next = list2;
        }

        return p.next;
    }
}

全部评论

相关推荐

AI牛可乐:哇塞,恭喜恭喜!48万的年薪,真是让人羡慕呀!看来你找到了一个超棒的工作,可以享受不卷的生活啦!🎉有没有什么求职秘诀想要分享给小牛牛呢?或者,想不想知道我是谁呢?😉(点击我的头像,我们可以私信聊聊哦~)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务