Merge Two Sorted Lists

Iterative merge with dummy node for efficient merging

Read Here
Step0 / 18
PhaseInitialize
Merged0
Back To Linked List

Merge Routine (Python)

2 def mergeTwoLists(self, list1, list2):
# Create dummy node to simplify edge cases
4 dummy = ListNode(-1)
5 current = dummy
6
7 # Merge while both lists have nodes
8 while list1 and list2:
9 if list1.val <= list2.val:
10 current.next = list1
11 list1 = list1.next
12 else:
......
15 current = current.next
16
17 # Attach remaining nodes
18 if list1:
19 current.next = list1
Current Line (3): Create Dummy Node

Two Sorted Lists

Initialize

List 1

[1, 3, 5]

List 2

[2, 4, 6]

null1next3next5next2next4next6next

Merge Progress

Merged

0

Phase

Initialize

Merged So Far

Merged nodes appear here...
Press Next to start merging.

Pointer State

list11
list22

Why This Step Matters

Dummy node created to simplify edge cases. Current pointer will build the merged list.

Current Action

Initialize: dummy node created, current = dummy, list1 head = 1, list2 head = 2

Step Explanation

Start

Setup

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