Merge Two Sorted Lists
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.
Example 1:
Example 2:
Example 3:
Constraints:
The number of nodes in both lists is in the range
[0, 50]
.-100 <= Node.val <= 100
Both
list1
andlist2
are sorted in non-decreasing order.
You can solve this problem by iterating through both linked lists simultaneously, comparing the values of their nodes, and building the merged list accordingly. Here's a JavaScript implementation using a dummy node:
In this implementation, the mergeTwoLists
function iterates through both lists, comparing the values of their nodes at each step. It builds the merged list by connecting nodes accordingly. Finally, it returns the head of the merged list.
Last updated