Optimal: dummy head and tail
Time O(n + m) Space O(1)tail starts at a dummy. While both lists have nodes, attach the smaller front node to tail and advance. Then attach the leftover list.
list1 = [1, 2, 4], list2 = [1, 3, 4]list2(list)
merged(list)
empty
Step 1/4Fronts: 1 and 1. Equal: take from list1 (keeps it stable).
class Solution {
public ListNode mergeTwoLists(ListNode a, ListNode b) {
ListNode dummy = new ListNode(0), tail = dummy;
while (a != null && b != null) {
if (a.val <= b.val) { tail.next = a; a = a.next; }
else { tail.next = b; b = b.next; }
tail = tail.next;
}
tail.next = (a != null) ? a : b;
return dummy.next;
}
}Verdict: Each node is attached once; no new nodes created.