AAlgoLoopSpaced repetition for LeetCode
EASYLinked ListLeetCode ↗

Merge Two Sorted Lists

The key idea

Both inputs are already sorted, so the next node of the answer is always the smaller of the two current heads. Splice that node in, advance only that list, and repeat. A dummy head node lets you append without special-casing the first node.

Problem

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

Constraints

Examples

Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4]
Input: list1 = [], list2 = [] Output: []
Input: list1 = [], list2 = [0] Output: [0]

Complexity

Time: O(n + m) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Linked List problems