Merge Two Sorted Linked Lists — Dummy Node Technique (Python, C, JS)
Problem Statement
Given heads of two sorted linked lists, merge them into one sorted list and return its head.
Example
Input: list1 = [1->2->4], list2 = [1->3->4]
Output: [1->1->2->3->4->4]
Time Complexity
O(n + m)
Space Complexity
O(1)
The Intuition
Dummy head node to avoid head-initialisation edge cases. Compare front nodes, attach smaller, advance that pointer.
Solution Code
def mergeTwoLists(l1, l2):
dummy = ListNode(0)
tail = dummy
while l1 and l2:
if l1.val < l2.val:
tail.next = l1; l1 = l1.next
else:
tail.next = l2; l2 = l2.next
tail = tail.next
tail.next = l1 or l2
return dummy.next
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
struct ListNode dummy; struct ListNode* tail = &dummy; dummy.next = NULL;
while (l1 && l2) {
if (l1->val < l2->val) { tail->next = l1; l1 = l1->next; }
else { tail->next = l2; l2 = l2->next; }
tail = tail->next;
}
tail->next = l1 ? l1 : l2;
return dummy.next;
}
function mergeTwoLists(l1, l2) {
const dummy = new ListNode(0);
let tail = dummy;
while (l1 && l2) {
if (l1.val < l2.val) { tail.next = l1; l1 = l1.next; }
else { tail.next = l2; l2 = l2.next; }
tail = tail.next;
}
tail.next = l1 || l2;
return dummy.next;
}
Frequently Asked Questions
Q: Why use a dummy node?
It avoids special-case logic for initialising the head of the merged list — tail.next handles every node uniformly.
Practice These Problems in a Real Curriculum
DoxaTech Hub's 10-month programme covers Data Structures, Algorithms, Python, C, SQL, and Full-Stack Development through 40 weeks of real, graded projects.
Get Started → More Problems