21. Merge Two Sorted Lists

🧩 Syntax:
/**
 * 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 mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 == null) return list2;
        if(list2 == null) return list1;
        
        PriorityQueue<ListNode> pq = new PriorityQueue<>((x, y) -> x.val - y.val);
        pq.add(list1);
        pq.add(list2);
        ListNode head = null;
        ListNode tail = null;

        while(pq.size() > 0){
            ListNode temp = pq.remove();
            if(temp.next != null){
                pq.add(temp.next);
            }
            if(head == null){
                head = temp;
                tail = head;
            }
            else{
                tail.next = temp;
                tail = tail.next;
            }
            tail.next = null;
        }
        return head;
    }
}