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 headNode = null;

        for (int i = 0; i < lists.size(); i++) {
            headNode = connectListNode(headNode, lists.get(i));
        }

        return headNode;
    }

    public ListNode connectListNode (ListNode node1, ListNode node2) {

        if (node1 == null || node2 == null) {
            return node1 == null ? node2 : node1;
        }

        if (node1.val < node2.val) {
            node1.next = connectListNode(node1.next, node2);
            return node1;
        } else {
            node2.next = connectListNode(node1, node2.next);
            return node2;
        }
    }
}