class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_two_sorted_lists(l1, l2):
dummy = ListNode() # dummy node to start merged list
tail = dummy # tail points to last node in merged list
while l1 and l2:
if l1.val < l2.val:
tail.next = l1 # attach l1 node
l1 = l1.next # move l1 forward
else:
tail.next = l2 # attach l2 node
l2 = l2.next # move l2 forward
tail = tail.next # move tail forward
tail.next = l1 if l1 else l2 # attach remaining nodes
return dummy.next
def print_list(head):
curr = head
result = []
while curr:
result.append(str(curr.val))
curr = curr.next
print(" -> ".join(result) + " -> null")
# Driver code
# Create list1: 1 -> 3 -> 5 -> null
l1 = ListNode(1, ListNode(3, ListNode(5)))
# Create list2: 2 -> 4 -> 6 -> null
l2 = ListNode(2, ListNode(4, ListNode(6)))
merged_head = merge_two_sorted_lists(l1, l2)
print_list(merged_head)keep comparing heads while both lists have nodes
choose smaller node to add next
attach l1 node to merged list
attach l2 node to merged list
move tail pointer forward to last node
tail.next = l1 if l1 else l2
attach remaining nodes after one list ends
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null