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 first two lists — do not allocate new nodes.
Return the head of the merged list.
[0, 5000].-10⁴ ≤ Node.val ≤ 10⁴list1 and list2 are sorted in non-decreasing order.Use a dummy head node and a tail pointer; repeatedly attach the smaller front node.
Both lists are sorted, so the smallest node of all is one of the two heads. Nothing deeper in either list can beat it. Compare the two heads, take the smaller one, and it's settled: it goes first in the answer.
Time O(n + m)Space O(1)
The full walkthrough and code are part of Premium