In place simple solution


  • 0
    Y

    Share my in-place version, please let me know what you think! Thanks

    public ListNode addLists(ListNode l1, ListNode l2) {
            int carry = 0;
            ListNode prev = null, ret = l1;
            while (l1 != null || l2 != null) {
                int sum = 0;
                if (l1 != null) {
                    sum = l1.val + carry;
                    if (l2 != null) {
                        sum += l2.val;
                        l2 = l2.next;
                    }
                    carry = sum / 10;
                    l1.val = sum % 10;
                    prev = l1;
                    l1 = l1.next;
                } else {
                    sum = l2.val + carry;
                    carry = sum / 10;
                    l2.val = sum % 10;
                    prev.next = l2;
                    prev = l2;
                    l2 = l2.next;
                }
            }
            if (carry > 0) {
                prev.next = new ListNode(carry);
            }
            return ret;
        }

Log in to reply
 

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