Merge Two Sorted Linked Lists Into One

Implement mergeTwoSortedLists

Given the heads of two sorted singly linked lists list1 and list2, merge them into a single sorted list and return its head. The merged list should be made by re-using the nodes of the original two lists — no new node values. Both inputs already arrive sorted, which is exactly the structure the optimal solution leans on: a two-pointer mergeTwo-Pointer MergeWalk two already-sorted sequences with one pointer each. At every step, the smaller of the two current elements is guaranteed to be the next-smallest element overall, so it can be appended immediately — no re-sorting, no lookahead. This is also the core building block behind merge sort. walks both lists side by side, always taking whichever current node holds the smaller value, and splices it directly into the result — turning two independent sorted chains into one sorted chain in a single O(n+m) pass with no extra nodes.

Example 1:

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

Output: [1,1,2,3,4,4]

Example 2:

Input: list1 = [], list2 = []

Output: []

Example 3:

Input: list1 = [], list2 = [0]

Output: [0]

+ 5 hidden test cases run on Submit.

Constraints:

  • 0 ≤ number of nodes in list1, list2 ≤ 50 each
  • -100 ≤ node value ≤ 100
  • Both list1 and list2 are sorted in non-decreasing order

list1 =

[1, 2, 4]

list2 =

[1, 3, 4]