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

## 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.
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)
{
a=a->next;
}
else
{
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;
}
};`````` #### 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.