you are given two linked lists representing two non-negative integers in reverse order. You need to add the two numbers and return the result as a linked list in reverse order. For example, if the input is (2 -> 4 -> 3) and (5 -> 6 -> 4), the output should be (7 -> 0 -> 8), which represents the sum of 342 and 465 in reverse order.
You can Try this:
**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
int val1 = (l1 != null) ? l1.val : 0;
int val2 = (l2 != null) ? l2.val : 0;
int sum = val1 + val2 + carry;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
l1 = (l1 != null) ? l1.next : null;
l2 = (l2 != null) ? l2.next : null;
}
return dummy.next;
}
}
Found this solution here(
https://www.techgeekbuzz.com/blog/co...iew-questions/)