You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list by splicing together the nodes of the two lists. Return the head of the merged linked list.
list1 = [1,2,4], list2 = [1,3,4][1,1,2,3,4,4]list1 = [1,3,5], list2 = [2,4,6][1,2,3,4,5,6]list1 = [], list2 = [0][0]dummy = new ListNode(0); set curr = dummy.p1 != null && p2 != null: enter comparison loop.p1.val ≤ p2.val: append p1 to result, advance p1.p2 to result, advance p2.dummy.next.Both input lists are already sorted. By always choosing the smaller front element, sorted order is maintained in the result. The dummy head eliminates special-casing the first insertion. When one list runs out, the remaining nodes of the other are already sorted — they can be appended directly as the tail without further comparisons.
Collecting all values, sorting them and building a new list costs O(n log n). Both lists are already sorted, so just merge.
Start with a dummy node and a tail pointer. Compare the two heads, attach the smaller one to the tail, and advance that list. When one list runs out, attach the rest of the other.
A dummy head makes building a list easy. Always take the smaller head.
Run the animation above on your own input, or watch the 1:11 video explanation of Merge Two Sorted Lists with a dry run and Java code.