Write a program to find the merge two sort Linked List || leetcode Solution || day 3 Challenge

 Given two sorted linked lists and return the sorted merge linked list




Approach and Algorithm :

we have used a very simple and easy approach which is a recursive method in this problem following the steps below

Step 1: from the beginning, we have checked the list1 and list2 conditions and returned the list. 

Step 2: After that, we again checked the condition if list1 of value  is less than list2 of value 

then using the recursive method and return the list1.

Step 3: Again using step 2 in the else condition and finally return the list2

Coding 

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        
        if(list1==nullptr)return list2;
        
        if(list2==nullptr)return list1;
        
        if(list1->val<list2->val){
            list1->next=mergeTwoLists(list1->next, list2);
            return list1;
        }
        
        else{
            list2->next=mergeTwoLists(list1, list2->next);
            return list2;
        }
    }
};


Post a Comment

0 Comments