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

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,

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 *