Java recursive solution


  • 0
    D
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if (l1 == null) {
                return l2;
            }
            if (l2 == null) {
                return l1;
            }
            ListNode head = new ListNode(0);
            int len1 = getListLength(l1);
            int len2 = getListLength(l2);
            addTwoNumbers(l1, len1, l2, len2, head);
            return head.val == 0 ? head.next : head;
        }
    
        private void addTwoNumbers(ListNode l1, int pos1, ListNode l2, int pos2, ListNode parent) {
            if (pos1 <= 0 || pos2 <= 0) {
                return;
            }
            ListNode here = new ListNode(0);
            if (pos1 == pos2) {
                addTwoNumbers(l1.next, pos1 - 1, l2.next, pos2 - 1, here);
                here.val += l1.val + l2.val;
            } else {
                if (pos1 > pos2) {
                    addTwoNumbers(l1.next, pos1 - 1, l2, pos2, here);
                } else {
                    addTwoNumbers(l1, pos1, l2.next, pos2 - 1, here);
                }
                here.val += pos1 > pos2 ? l1.val : l2.val;
            }
            if (here.val >= 10) {
                parent.val++;
                here.val -= 10;
            }
            parent.next = here;
        }
    
        private int getListLength(ListNode list) {
            int len = 0;
            while (list != null) {
                len++;
                list = list.next;
            }
            return len;
        }
    }
    

Log in to reply
 

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