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
Subscribe to see which companies asked this question
My Solution
/**
* 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) {
ListNode re=new ListNode(0);
int carry=0;
ListNode now=re;
while(l1!=null||l2!=null){
if(l1!=null){
carry+=l1.val;
l1=l1.next;
}
if(l2!=null){
carry+=l2.val;
l2=l2.next;
}
if(carry>=10){
now.val=carry-10;
carry=1;
}
else{
now.val=carry;
carry=0;
}
if(l1!=null||l2!=null){
ListNode next=new ListNode(0);
now.next=next;
now=next;
}
}
if(carry==1)
now.next=new ListNode(1);
return re;
}
}