题解 | #合并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 == null || lists.size() == 0) {
            return null;
        }
        ListNode newHead = new ListNode(-1);
        newHead.next = lists.get(0);
        ListNode temp = newHead.next;
        for (int i = 1; i < lists.size(); i++) {
            ListNode node = newHead;
            ListNode cur = lists.get(i);
            while (temp != null && cur != null) {
                if (temp.val < cur.val) {
                    node.next = temp;
                    temp = temp.next;
                } else {
                    node.next = cur;
                    cur = cur.next;
                }
                node = node.next;
            }
            if (temp != null) {
                node.next = temp;
            }
            if (cur != null) {
                node.next = cur;
            }
            temp = newHead.next;
        }
        return newHead.next;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-18 18:30
点赞 评论 收藏
分享
07-22 13:50
门头沟学院 Java
仁者伍敌:其实能找到就很好了,当然收支能抵
点赞 评论 收藏
分享
点赞 评论 收藏
分享
07-15 00:33
江苏大学 Java
代码飞升:哈哈哈哈评论区三个打广告的
简历中的项目经历要怎么写
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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