package leetcode.oj.addTwoNumbers;

//http://oj.leetcode.com/problems/add-two-numbers/

public class Solution {
	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

		if (l1 == null || l2 == null)
			return null;

		ListNode head = new ListNode(-1);
		ListNode current = head;

		int appendix = 0;

		while (true) {
			if (l1 == null || l2 == null)
				break;

			int l1val = l1.val;
			int l2val = l2.val;
			l1 = l1.next;
			l2 = l2.next;

			int sum = l1val + l2val;
			int res = sum;
			if (sum >= 10) {
				res = sum % 10;
			}

			ListNode nod = new ListNode(res + appendix);
			current.next = nod;
			current = current.next;

			if (sum > 10) {
				appendix = 1;
			}
		}

		if (l1 != null) {
			l1.val += appendix;
			current.next = l1;
		}

		if (l2 != null) {
			l2.val += appendix;
			current.next = l2;
		}

		if (l1 == null && l2 == null) {
			if (appendix != 0) {
				ListNode no = new ListNode(appendix);
				current.next = no;
			}

		}
		return head.next;
	}

}

class ListNode {
	int val;
	ListNode next;

	ListNode(int x) {
		val = x;
		next = null;
	}
}
@@ -468,16 +468,27 @@
  + l2val
+ + appendix
 ;%0A%09%09%09int
@@ -579,27 +579,16 @@
 Node(res
- + appendix
 );%0A%09%09%09cu
@@ -645,16 +645,17 @@
 f (sum %3E
+=
  10) %7B%0A%09
@@ -679,55 +679,28 @@
 %09%09%09%7D
-%0A%09%09%7D%0A%0A%09%09if (l1 != null) %7B%0A%09%09%09l1.val += 
+ else %7B%0A%09%09%09%09
 appendix
 ;%0A%09%09
@@ -699,47 +699,48 @@
 ndix
+ = 0
 ;%0A%09%09%09
-current.next = l1;%0A%09%09%7D%0A%0A%09%09if (l2 !
+%7D%0A%09%09%7D%0A%0A%09%09if (l1 == null && l2 =
 = nu
@@ -752,26 +752,68 @@
 %0A%09%09%09
-l2.val += 
+if (appendix != 0) %7B%0A%09%09%09%09ListNode no = new ListNode(
 appendix
 ;%0A%09%09
@@ -808,18 +808,20 @@
 appendix
+)
 ;%0A
+%09
 %09%09%09curre
@@ -834,92 +834,80 @@
 t = 
-l2
+no
 ;%0A
+%09
 %09%09%7D%0A%0A%09%09
-if (l1 == null && l2 == null) %7B%0A%09%09%09if (appendix != 0) %7B%0A%09%09%09%09ListNode no =
+%7D else if (l1 != null) %7B%0A%09%09%09current.next = addTwoNumbers(l1,
  new
@@ -929,43 +929,104 @@
 dix)
+)
 ;%0A%09%09
-%09%09current.next = no
+%7D else if (l2 != null) %7B%0A%09%09%09current.next = addTwoNumbers(l2, new ListNode(appendix))
 ;%0A
-%09
 %09%09%7D%0A%0A
-%09%09%7D%0A
 %09%09re

add code