Java solution with less additional memory


  • 0
    S
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode result = l1;
            ListNode current = null;
            
            int additive = 0;
            while (l1 != null) {
                l1.val = l1.val + (l2 == null ? 0 : l2.val) + additive;
                additive = l1.val / 10;
                l1.val = l1.val % 10;
                if (current != null) 
                    current.next = l1;
                current = l1;
                
                l1 = l1.next;
                if (l2 != null) l2 = l2.next;                
                
                //swap if l2 longer
                if (l1 == null && l2 != null) {
                    l1 = l2;
                    l2 = null;
                }
            }
            
            if (additive > 0)
                current.next = new ListNode(additive);    
            
            return result;
        }
    }
    

Log in to reply
 

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