C# 63ms Accepted Solution


  • 1
    L
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
            if (l2 == null) return l1;
            if (l1 == null) return l2;
            ListNode p11 = l1;
            ListNode p12 = p11.next;
            ListNode p21 = l2;
            ListNode p22 = l2.next;
    
            if (p21.val <= p11.val)
            {
                if (p22 != null)
                {
                    while (p22.val <= p11.val)
                    {
                        p21 = p21.next;
                        p22 = p22.next;
                        if (p22 == null) break;
                    }
                }
                p21.next = p11;
                l1 = l2;
    
                l2 = p22;
                p21 = p22;
            }
    
            while (p21 != null)
            {
                if (p12 == null)
                {
                    p11.next = p21;
                    return l1;
                }
                else
                {
                    while (p12.val < p21.val)
                    {
                        p11 = p11.next;
                        p12 = p12.next;
                        if (p12 == null) break;
                    }
                    if (p12 != null)
                    {
                        p22 = p21.next;
                        p21.next = p12;
                        p11.next = p21;
                        p11 = p21;
                        p21 = p22;
                    }
                }
            }
    
            return l1;
        }
    }

Log in to reply
 

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