Merge Two Sorted Lists
easy · dummy node / two pointers
You are given the heads of two sorted linked lists (non-decreasing order). Merge them into a single sorted linked list by splicing the existing nodes together — do not create new nodes or copy values. Return the head of the merged list. Either or both lists may be empty. The nodes are ListNode objects with val and next.
Constraints
0 ≤ nodes in each list ≤ 50; -100 ≤ val ≤ 100.
Examples
[1,2,4]+[1,3,4] → [1,1,2,3,4,4]
[]+[] → []
[]+[0] → [0]
Starter code
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_two_lists(list1: ListNode | None, list2: ListNode | None) -> ListNode | None:
pass
Loading editor…
Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.
Return to the Python interpreter