Mid From PDF Coding C# Coding Interview

Merge k sorted linked lists into one sorted linked list?

ListNode MergeKLists(ListNode[] lists) {
if (lists == null || lists.Length == 0) return null;

PriorityQueue<ListNode, int> pq = new PriorityQueue<ListNode,

int>();
foreach (var list in lists)
if (list != null)

pq.Enqueue(list, list.val);

ListNode dummy = new ListNode(0);
ListNode current = dummy;

while (pq.Count > 0) {

var node = pq.Dequeue();
current.next = node;
current = current.next;
if (node.next != null)

pq.Enqueue(node.next, node.next.val);

}
return dummy.next;
}

Follow on:

Explanation:

Use a min-heap (priority queue) to always pick the smallest head node among k lists.

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details