Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists in a 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:
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]
Constraints:
[0, 50]
.-100 <= Node.val <= 100
list1
and list2
are sorted in non-decreasing order.class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
// if list1 happen to be NULL
// we will simply return list2.
if(l1 == NULL)
{
return l2;
}
// if list2 happen to be NULL
// we will simply return list1.
if(l2 == NULL)
{
return l1;
}
// if value pointend by l1 pointer is less than equal to value pointed by l2 pointer
// we wall call recursively l1 -> next and whole l2 list.
if(l1 -> val <= l2 -> val)
{
l1 -> next = mergeTwoLists(l1 -> next, l2);
return l1;
}
// we will call recursive l1 whole list and l2 -> next
else
{
l2 -> next = mergeTwoLists(l1, l2 -> next);
return l2;
}
}
};
public ListNode mergeTwoLists(ListNode l1, ListNode l2){
if(l1 == null) return l2;
if(l2 == null) return l1;
if(l1.val < l2.val){
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else{
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
def mergeTwoLists1(self, l1, l2):
dummy = cur = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2
return dummy.next
In our experience, we suggest you solve this Merge Two Sorted Lists LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Merge Two Sorted Lists LeetCode Solution
I hope this Merge Two Sorted Lists LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>