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

合并k个已排序的链表

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

using System;
using System.Collections.Generic;

/*
public class ListNode
{
    public int val;
    public ListNode next;

    public ListNode (int x)
    {
        val = x;
    }
}
*/

class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param lists ListNode类一维数组
     * @return ListNode类
     */
    public ListNode mergeKLists (List<ListNode> lists) {
        int k = lists.Count;
        if (k == 0) return null;
        while (k > 1) {
            for (int i = 0; i < k / 2; i++) {
                lists[i] = MergeTwoLists(lists[2 * i], lists[2 * i + 1]);
            }
            if (k % 2 != 0) {
                lists[k / 2] = lists[k - 1];
                k = k / 2 + 1;
                continue;
            }
            k = k / 2;
        }
        return lists[0];
    }
    public ListNode MergeTwoLists(ListNode list1, ListNode list2) {
        ListNode newHead = new ListNode(0);
        ListNode cur = newHead;
        while (true) {
            if (list1 == null) {
                cur.next = list2;
                break;
            }
            if (list2 == null) {
                cur.next = list1;
                break;
            }
            if (list1.val > list2.val) {
                cur.next = list2;
                cur = cur.next;
                list2 = list2.next;
            } else {
                cur.next = list1;
                cur = cur.next;
                list1 = list1.next;
            }
        }
        return newHead.next;
    }
}

全部评论

相关推荐

孤寡孤寡的牛牛很热情:为什么我2本9硕投了很多,都是简历或者挂,难道那个恶心人的测评真的得认真做吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务