JAVA not recursive version easy understant


  • 0
    B
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode start = new ListNode(0);
            ListNode ptr = start;
            while(l1!=null&&l2!=null)
            {
                if(l1.val>l2.val)
                {
                    ptr.next = new ListNode(l2.val);
                    ptr = ptr.next;
                    l2 = l2.next;
                }
                else
                {
                    ptr.next = new ListNode(l1.val);
                    ptr = ptr.next;
                    l1 = l1.next;                
                }
            }
            if(l2==null)
                ptr.next = l1;
            else
                ptr.next = l2;
            return start.next;
        }
    

  • 0
    G

    Hi,your code is closely to mine,but i juge if null in while,so why there is no NPE in this
    programe?


Log in to reply
 

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