Simple C++ Solution with comments


  • 0
    N
    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            ListNode *head = nullptr;
            
            //If any of the lists is empty, return the other list.
            if(!l1 && !l2) return l1;
            if(!l1 && l2) return l2;
            if(!l2 && l1) return l1;
            
            //For selecting the head of the merged list
            if(l1->val < l2->val) {
                head = l1;
                l1 = l1->next;
            }
            else {
                head = l2;
                l2 = l2->next;
            }
            
            //For rest of the nodes, compare and insert into the new list
            ListNode *temp = head;
            while(l1 && l2) {
                if(l1->val < l2->val) {
                    temp->next = l1;
                    l1 = l1->next;
                }
                else {
                    temp->next = l2;
                    l2 = l2->next;
                }
                 temp = temp->next;
            }
    
            //For the remaining nodes, for unequal length of lists
            if(l1) {
                while(l1)
                   {temp->next = l1; l1 = l1->next; temp = temp->next;}}
            if(l2) {
                while(l2) 
                   {temp->next = l2; l2 = l2->next; temp = temp->next;}}
            
            return head;
        }
    };
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.