A simple easy understand Java solution with O(1) space


  • 0
    1. Scan two lists and always assign l1 pointer to the longest one.
    2. Recursively update left digits.
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode head = new ListNode(-1);
            ListNode temp;
            if (listLen(l1) < listLen(l2)){
                temp = l1;
                l1 = l2;
                l2 = temp;
            } 
            head.next = l1;
            while (l1 != null && l2 != null){
                l1.val = l1.val + l2.val;
                if (l1.val >= 10){
                    ListNode p = l1;
                    plusOne(p, l1.val);
                }
                l1 = l1.next;
                l2 = l2.next;
            }
            return head.next;
        }
        private int listLen (ListNode i){
            int count = 0;
            while (i != null){
                count++;
                i = i.next;
            }
            return count;
        }
        private void plusOne (ListNode i, int value){
            if (value < 10){
                return;
            } 
            i.val = value % 10;
            if (i.next == null){
                i.next = new ListNode(1);
                return;
            }
            i.next.val += 1;
            plusOne(i.next, i.next.val);
        }
    }
    

Log in to reply
 

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