Merge Two Sorted Lists LeetCode Solution

Here, We see Merge Two Sorted Lists LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with a different approach.

List of all LeetCode Solution

Merge Two Sorted Lists LeetCode Solution

Merge Two Sorted Lists LeetCode Solution

Problem Statement

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.

Merge Two Sorted Lists ex1
fig-1
Example 1: (fig-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]

Merge Two Sorted Lists Leetcode Solution C++

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        if(list1 == NULL) return list2;
        if(list2 == NULL) return list1;
        if(list1->val>=list2->val) list2->next = mergeTwoLists(list1, list2-> next);
        else{
            list1->next = mergeTwoLists(list1->next, list2);
            list2 = list1;
        }return list2;
    }
};
Code language: C++ (cpp)

Merge Two Sorted Lists Leetcode Solution Java

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
		if(list1 == null) return list2;
		if(list2 == null) return list1;
		if(list1.val < list2.val){
			list1.next = mergeTwoLists(list1.next, list2);
			return list1;
		} else{
			list2.next = mergeTwoLists(list1, list2.next);
			return list2;        
    }
    }
}
Code language: Java (java)

Merge Two Sorted Lists Leetcode Solution JavaScript

var mergeTwoLists = function(list1, list2) {
    var mergedHead = { val : -1, next : null },
        crt = mergedHead;
    while(list1 && list2) {
        if(list1.val > list2.val) {
            crt.next = list2;
            list2 = list2.next;
        } else {
            crt.next = list1;
            list1 = list1.next;
        }
        crt = crt.next;
    }
    crt.next = list1 || list2;
    
    return mergedHead.next;    
};
Code language: JavaScript (javascript)

Merge Two Sorted Lists Leetcode Solution Python

class Solution(object):
    def mergeTwoLists(self, list1, list2):
        dummy = cur = ListNode(0)
        while list1 and list2:
            if list1.val < list2.val:
                cur.next = list1
                list1 = list1.next
            else:
                cur.next = list2
                list2 = list2.next
            cur = cur.next
        cur.next = list1 or list2
        return dummy.next
Code language: Python (python)
Scroll to Top