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,
- Leetcode Merge Two Sorted Lists problem solution in C
- Leetcode Merge Two Sorted Lists problem solution in Java
- Leetcode Merge Two Sorted Lists problem solution in Python
- Leetcode Merge Two Sorted Lists problem solution in C#