Simple and Readable Solution in Java


#1
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     public int val;
 *     public ListNode next;
 *     ListNode(int x) { val = x; next = null; }
 * }
 */
public class Solution {
    ListNode newList = null;
    ListNode prev = null;
    int carry = 0;
    private void supportFunction(int sum) {
        int rem = sum % 10;
        carry = sum / 10;
        ListNode node = new ListNode(rem);
        if(newList == null) {
            newList = node;
            prev = newList;
        } else {
            prev.next = node;
            prev = prev.next;
            node = node.next;
        }
    }
    public ListNode addTwoNumbers(ListNode A, ListNode B) {
        
        // Create new Linked List
        ListNode a = A;
        ListNode b = B;
        
        while(a != null && b != null) {
            supportFunction(a.val + b.val + carry);
            a = a.next;
            b = b.next;
        }
        if(a == null && b != null) {
            while(b != null) {
                supportFunction(b.val + carry);
                b = b.next;
            }
        }
        if(b == null && a != null) {
            while(a != null) {
                supportFunction(a.val + carry);
                a = a.next;
            }
        }
        if(carry != 0) {
            supportFunction(carry);
        }
        return newList;
    }
}