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
public class Solution {
public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
ListNode l1curr = l1;
ListNode l2curr = l2;
ListNode head = null;
ListNode tail = null;
while(l1curr != null || l2curr!=null)
{
ListNode nextNode = null;
//if both are not null then take nextNode from smaller one
if(l1curr != null && l2curr != null)
{
if(l1curr.val < l2curr.val)
{
nextNode = l1curr;
l1curr = l1curr.next;
}
else
{
nextNode = l2curr;
l2curr = l2curr.next;
}
}
//if l1curr is still not empty then take it from it
else if(l1curr != null)
{
nextNode = l1curr;
l1curr = l1curr.next;
}
//if l2curr is still not empty then take it from it
else if(l2curr != null)
{
nextNode = l2curr;
l2curr = l2curr.next;
}
//initially if head is null, point to both head and tail
if(head == null)
{
head = tail = nextNode;
}
else
{
tail.next = nextNode;
tail = nextNode;
}
}
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