# 23. Merge k Sorted Lists

{% hint style="info" %}
PriorityQueue data structure
{% endhint %}

```java
/**
 * 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 method:
        // queue.poll()
        // queue.add()
        // queue.isEmpty()
        // queue.peek()
        ListNode  head = new ListNode();
        ListNode result = head;
        if(lists.length==0) return result.next;
        PriorityQueue<ListNode> priorityQueue=new PriorityQueue<>(lists.length, (a,b)->a.val-b.val);
        for(ListNode node: lists){
            // null node is not legal
            if (node!=null){
               priorityQueue.add(node); 
            }
        }
        
        while(!priorityQueue.isEmpty()){
            ListNode topNode = priorityQueue.poll();
            head.next=topNode;
            head=head.next;
            if(topNode.next!=null){
                priorityQueue.add(topNode.next);
            }
        }
        return result.next;
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ucan.gitbook.io/notes/linkedlist/23.-merge-k-sorted-lists.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
