An interactive visualization of the merge technique using a dummy head node. Watch how two sorted linked lists are merged into one sorted list by comparing nodes and linking them together.
Linked List LeetCode 21 โ Easylist1 and list2.fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? { val dummy = ListNode(0) var current = dummy var l1 = list1 var l2 = list2 while (l1 != null && l2 != null) { if (l1.`val` <= l2.`val`) { current.next = l1 l1 = l1.next } else { current.next = l2 l2 = l2.next } current = current.next!! } current.next = l1 ?: l2 return dummy.next}
The dummy head technique eliminates the need for special-case logic when building a new linked list.
By creating a placeholder node at the start, we always have a valid current pointer to attach
the next node to, and the real head of the merged list is simply dummy.next.
dummy node and set current = dummy. This dummy node acts as a placeholder head for the merged list.current.next and advance that list's pointer.current to current.next so the next node can be appended.current.next.dummy.next is the head of the merged sorted list (skipping the dummy placeholder).
We visit each node exactly once across both lists, giving O(n + m) time where n and m are the lengths
of the two lists. We only use a constant number of pointers โ no extra data structures needed.