• Add Two Numbers

Add Two Numbers

You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Solution:
1. /*
2. * Definition for singly-linked list.
3. * public class ListNode {
4. * int val;
5. * ListNode next;
6. * ListNode(int x) { val = x; }
7. * }
8.
/
9. public class Solution {
10. public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
11. ListNode f = new ListNode(0);
12. ListNode p = f;
13. 14. int c = 0;
15. 16. while (l1 != null || l2 != null || c != 0) {
17. int a = (l1 == null) ? 0 : l1.val;
18. int b = (l2 == null) ? 0 : l2.val;
19. int s = a + b + c;
20. 21. p.next = new ListNode(s % 10);
22. p = p.next;
23. 24. if (l1 != null) l1 = l1.next;
25. if (l2 != null) l2 = l2.next;
26. 27. c = s / 10;
28. }
29. 30. return f.next;
31. }
32. }