I'm trying to implement a function to add two numbers represented as reverse linked lists. In my opinion the code is correct but on giving input with both linkedlist consisting of just one number [5] . The output is coming out to be [0], but it's supposed to be [0]->[1]
Example First List: 5->6->3 // represents number 365 Second List: 8->4->2 // represents number 248 . Resultant list: 3->1->6 // represents number 613
can someone tell me what I'm doing wrong in the logic?`
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//find length
int carry = 0;
ListNode sum = null;
int x = 0;
ListNode top = new ListNode(0);
while(l1 != null || l2 != null){
sum = new ListNode((l1.val+l2.val+carry)%10);
// sum.val = (l1+l2+carry)%10;
if(x==0){
top.next = sum;
x++;
}
carry = (l1.val+l2.val)/10;
l1 = l1.next;
l2 = l2.next;
sum = sum.next;
}
if(l1 == null && l2 == null){
//return top;
}else if(l1 != null && l2 == null){
while(l1 != null){
sum = new ListNode((l1.val+carry)%10);
// sum.val = (l1+carry)%10;
if(x==0){
top.next = sum;
x++;
}
carry = (l1.val)/10;
l1 = l1.next;
sum = sum.next;
}
//return top;
}else{
while(l1 != null){
sum = new ListNode((l2.val+carry)%10);
// sum.val = (l2+carry)%10;
if(x==0){
top.next = sum;
x++;
}
carry = (l2.val)/10;
l2 = l2.next;
sum = sum.next;
}
//return top;
}
if(carry == 1){
sum = new ListNode(1);
sum = sum.next;
}
return top.next;
}
}`