Java O(n) remedy interval then recursive


  • 0
    G
     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode n1 = l1, n2 = l2;
            for (; n1 != null && n2 != null; n1 = n1.next, n2 = n2.next) ; // until someone is null
    
            ListNode remedy = new ListNode(0), r = remedy;
    
            for (ListNode s = (n1 == null ? n2 : n1)
                 ; s != null; s = s.next)
    
                r = (r.next = new ListNode(0));           // remedy shorter listnode by add node(0)
    
    
            r.next = n2 == null ? l2 : l1;
            ListNode result = doAdd(remedy.next, n2 == null ? l1 : l2);   // comfy recursive
    
            if (result.val > 9) {              // carry bit
                ListNode precede = new ListNode(1);
                precede.next = result;
                result.val = result.val - 10;
                return precede;
            }
            return result;
        }
        
         private static ListNode doAdd(ListNode l1, ListNode l2) {
           if (l1 == null && l2 == null)
                return null;
    
            ListNode later = doAdd(l1.next, l2.next);
            if (later == null)
                return new ListNode(l1.val + l2.val);
    
            ListNode cur = new ListNode((later.val / 10) + l1.val + l2.val);    // later node value > 9 ,cur +1
            later.val = later.val % 10;      // then reset later node 
            cur.next = later;
            return cur;
        }
    

Log in to reply
 

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