Leetcode 23: Merge K Sorted Lists (Java)

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

Solution:

For this problem, the brute force solution would be passing all the lists and perform Merge Sort, but for the optimal solution we will use minHeap using PriorityQueue data structure.

Note: Please try to solve it yourself before looking into the solution below

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
        
        for(ListNode head: lists){
            while(head!=null){
                minHeap.offer(head.val);
                head = head.next;
            }
        }
        
        ListNode returnNode = new ListNode(-1);
        ListNode head = returnNode;
        
        while(!minHeap.isEmpty()){
            head.next = new ListNode(minHeap.remove());
            head = head.next;
        }
        
        return returnNode.next;
    }
}