Recursive O(Max length of the two given LinkedList) Java Solution


  • 0
    J
    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if (l1 == null) return l2;
            if (l2 == null) return l1;
            return addTwoNumbersHelper(l1, l2, 0);    
        }
        
        private ListNode addTwoNumbersHelper(ListNode l1, ListNode l2, int carry) {
            if (l1 == null && l2 == null && carry == 0) return null;
            int sum = 0;
            if (l1 != null) {
                sum += l1.val;
            }
            if (l2 != null) {
                sum += l2.val;
            }
            sum += carry;
            int value = sum % 10;
            carry = sum / 10;
            ListNode head = new ListNode(value);
            head.next = addTwoNumbersHelper(l1 != null ? l1.next : null, l2 != null ? l2.next : null, carry);
            return head;
        }
        
        
    }
    

Log in to reply
 

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