Leetcode Merge Two Sorted Lists problem solution in C++ programming

In the Leetcode Merge Two Sorted Lists problem solution in C++ programming 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.

Leetcode Merge Two Sorted Lists problem solution in C++ programming

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* a, ListNode* b) {
        //If one of the two linked lists are NULL, merging not possible.
        ListNode*head=NULL,*tail=NULL;
        if(!a) return b;
        if(!b) return a;
        //Assigning head node to the node with the smallest first node value
        if(a->val<=b->val)
        {
            head=tail=a;
            a=a->next;
        }
        else
        {
            head=tail=b;
            b=b->next;
        }
        //Now, merging.
        while(a&&b)
        {
            if(a->val<=b->val)
            {
                tail->next=a;
                tail=a;
                a=a->next;
            }
            else
            {
                tail->next=b;
                tail=b;
                b=b->next;
            }
        }
        //If any of the list reaches null, then we can simply attach the remaining list.
        if(!a) 
            tail->next=b;
        else
            tail->next=a;
        return head;
    }
};

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *