package ListNode;

//2. Add Two Numbers
/**
 * You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
 * 
 * You may assume the two numbers do not contain any leading zero, except the number 0 itself.
 * 
 * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
 * Output: 7 -> 0 -> 8
 * 
 * Tags:  Linked List, Math
 * Similar Problems:  (M) Multiply Strings (E) Add Binary (E) Sum of Two Integers (E) Add Strings (M) Add Two Numbers II
 * 
 * @author Xinyue Zhang
 *
 */

//ListNode class
/**
package ListNode;

public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
    
    public static void insertList(int val, ListNode head) {
        ListNode node = new ListNode(0);
        node.val = val;
        while (head.next != null)
            head = head.next;
        head.next = node;
    }
}**/

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode prev = new ListNode(0);
        ListNode head = prev;
        int carry = 0, sum = 0;
        
        while (l1 != null || l2 != null || carry != 0) {
            sum = carry + ((l1 == null) ? 0 : l1.val) + ((l2 == null) ? 0 : l2.val);
            carry = sum / 10;
            
            prev.next = new ListNode(sum % 10);
            prev = prev.next;
            
            l1 = l1 == null ? l1 : l1.next;
            l2 = l2 == null ? l2 : l2.next;
        }
        return head.next;
    }
    
    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        ListNode.insertList(4, l1);
        ListNode.insertList(3, l1);
        
        ListNode l2 = new ListNode(5);
        ListNode.insertList(6, l2);
        ListNode.insertList(4, l2);
        
        System.out.println("Sum = ");
        ListNode sum = new ListNode(0);
        Solution sol = new Solution();
        sum = sol.addTwoNumbers(l1, l2);
        while (sum != null) {
            System.out.println(sum.val);
            sum = sum.next;
        }
    }
}

@@ -752,50 +752,22 @@
     
-%0A    public static void insert
 List
+Node
 (int 
-val
+x
 , Li
@@ -777,158 +777,25 @@
 ode 
-head) %7B%0A        ListNode node = new ListNode(0);%0A        node.val = val;%0A        while (head.next != null)%0A            head = head.next;%0A        head.
+node) %7B val = x; 
 next
@@ -802,22 +802,23 @@
  = node;
+ %7D
 %0A    
-%7D
 %0A%7D**/%0A%0Ap
@@ -1509,81 +1509,67 @@
 ode(
-2);%0A        ListNode.insertList(4, l1);%0A        ListNode.insertList(3
+3), l1_1 = new ListNode(4, l1), l1_2 = new ListNode(2
 , l1
+_1
 );%0A 
@@ -1615,81 +1615,67 @@
 ode(
-5);%0A        ListNode.insertList(6, l2);%0A        ListNode.insertList(4
+4), l2_1 = new ListNode(6, l2), l2_2 = new ListNode(5
 , l2
+_1
 );%0A 
@@ -1833,20 +1833,24 @@
 mbers(l1
+_2
 , l2
+_2
 );%0A     

Update 002_Add_Two_Numbers.java