# Merge Two Sorted Lists Leetcode Solution

In this post, we are going to solve the Merge Two Sorted Lists Leetcode Solution problem of Leetcode. This Leetcode problem is done in many programming languages like C++, Java, and Python.

## Problem

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.

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 = 
Output: 
```

Constraints:

• The number of nodes in both lists is in the range `[0, 50]`.
• `-100 <= Node.val <= 100`
• Both `list1` and `list2` are sorted in non-decreasing order.

Now, lets see the leetcode solution of Merge Two Sorted Lists Leetcode Solution.

### Merge Two Sorted Lists Leetcode Solution in Python

```# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
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```

### Merge Two Sorted ListsLeetcode Solutionin CPP

```/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode() : val(0), next(nullptr) {}
*     ListNode(int x) : val(x), next(nullptr) {}
*     ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* temp = new ListNode(-1);
while(l1!=NULL and l2!=NULL){
if(l1->val<=l2->val){
l1 = l1->next;
}
else {
l2 = l2->next;
}
}
if(l1!=NULL)
{
}

return temp->next;
}
};```

### Merge Two Sorted Lists Leetcode Solution in Java

```/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode() {}
*     ListNode(int val) { this.val = val; }
*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
while(l1 != null && l2 != null) {
if (l1.val <= l2.val) {
handler.next = l1;
l1 = l1.next;
} else {
handler.next = l2;
l2 = l2.next;
}
handler = handler.next;
}

if (l1 != null) {
handler.next = l1;
} else if (l2 != null) {
handler.next = l2;
}