Iterative
Intuition
We use a dummy head node to simplify the merging logic, then compare the heads of both lists one step at a time. At each step, we attach the smaller node to our result list and advance that list's pointer. This is similar to the merge step in merge sort. The dummy node avoids special-casing the head of the result list -- at the end, we simply return dummy.next. After one list is exhausted, we attach the remainder of the other list directly since it is already sorted.
Algorithm
- Create a dummy node to serve as the head of the merged list. Initialize a 'current' pointer to the dummy node.
- While both list1 and list2 are non-null, compare their values.
- Attach the node with the smaller value to current.next and advance that list's pointer.
- Advance the current pointer to current.next.
- When the loop ends, one list may still have remaining nodes. Attach it to current.next.
- Return dummy.next as the head of the merged list.
O(n + m)SpaceO(1)Code (C++ · Java · Python · Go)
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode dummy(-1);
ListNode* current = &dummy;
while (list1 != nullptr && list2 != nullptr) {
if (list1->val <= list2->val) {
current->next = list1;
list1 = list1->next;
} else {
current->next = list2;
list2 = list2->next;
}
current = current->next;
}
current->next = (list1 != nullptr) ? list1 : list2;
return dummy.next;
}
};class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode(-1);
ListNode current = dummy;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
current.next = list1;
list1 = list1.next;
} else {
current.next = list2;
list2 = list2.next;
}
current = current.next;
}
current.next = (list1 != null) ? list1 : list2;
return dummy.next;
}
}def mergeTwoLists(list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(-1)
current = dummy
while list1 and list2:
if list1.val <= list2.val:
current.next = list1
list1 = list1.next
else:
current.next = list2
list2 = list2.next
current = current.next
current.next = list1 if list1 else list2
return dummy.nextfunc mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
dummy := &ListNode{}
current := dummy
for list1 != nil && list2 != nil {
if list1.Val <= list2.Val {
current.Next = list1
list1 = list1.Next
} else {
current.Next = list2
list2 = list2.Next
}
current = current.Next
}
if list1 != nil {
current.Next = list1
} else {
current.Next = list2
}
return dummy.Next
}