Merge Two Sorted Lists
Iterative merge with dummy node for efficient merging
Merge Routine (Python)
2 def mergeTwoLists(self, list1, list2):● # Create dummy node to simplify edge cases4 dummy = ListNode(-1)5 current = dummy6 7 # Merge while both lists have nodes8 while list1 and list2:9 if list1.val <= list2.val:10 current.next = list111 list1 = list1.next12 else:......15 current = current.next16 17 # Attach remaining nodes18 if list1:19 current.next = list1Current Line (3): Create Dummy Node
Two Sorted Lists
Initialize
List 1
[1, 3, 5]
List 2
[2, 4, 6]
Merge Progress
Pointer State
Step Explanation
StartSetup
Create dummy node and initialize pointers for merging.
- > Phase: Initialize
- > Dummy node simplifies edge cases.
- > current will build the merged result.
Unvisited
Current
List1
List2
Merged
Done