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;
    }
}