C# Accepted solution, beats 95%


  • 0
    A
    public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
            if (l1 == null && l2 == null) return null;
                if (l1 == null) return l2;
                if (l2 == null) return l1;
    
                ListNode result;
                var nextL1 = l1;
                var nextL2 = l2;
                if (l1.val < l2.val)
                {
                    result = new ListNode(l1.val);
                    nextL1 = l1.next;
                }
                else
                {
                    result = new ListNode(l2.val);
                    nextL2 = l2.next;
                }
                var temp = result;
                while (nextL1 != null || nextL2 != null)
                {
                    if (nextL1 == null)
                    {
                        temp.next = nextL2;
                        return result;
                    }
                    else if (nextL2 == null)
                    {
                        temp.next = nextL1;
                        return result;
                    }
                    else
                    {
                        if (nextL1.val < nextL2.val)
                        {
                            temp.next = nextL1;
                            nextL1 = nextL1.next;
                            temp = temp.next;
                        }
                        else
                        {
                            temp.next = nextL2;
                            nextL2 = nextL2.next;
                            temp = temp.next;
                        }
                    }
                }
               
    
                return result;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.