Last updated on October 10th, 2024 at 02:01 am
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
Topics
Linked List
Companies
Amazon, Apple, LinkedIn, Microsoft
Level of Question
Easy
Merge Two Sorted Lists LeetCode Solution
Table of Contents
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.
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]
1. 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; } };
2. 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; } } }
3. 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; };
4. 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