You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored inforward
order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
Copy public ListNode addLists2(ListNode l1, ListNode l2) {
if(l1==null && l2==null){
return null;
}
ListNode dummy=new ListNode(0);
ListNode current=dummy;
int carry=0;
l1=reverse(l1);
l2=reverse(l2);
while(l1!=null && l2!=null){
int sum=l1.val+l2.val+carry;
carry=sum/10;
current.next=new ListNode(sum%10);
l1=l1.next;
l2=l2.next;
current=current.next;
}
while(l1!=null){
int sum=l1.val+carry;
carry=sum/10;
current.next=new ListNode(sum%10);
l1=l1.next;
current=current.next;
}
while(l2!=null){
int sum=l2.val+carry;
carry=sum/10;
current.next=new ListNode(sum%10);
l2=l2.next;
current=current.next;
}
if(carry!=0){
current.next=new ListNode(carry);
}
return reverse(dummy.next);
}
public ListNode reverse(ListNode head){
ListNode prev=null;
while(head!=null){
ListNode temp=head.next;
head.next=prev;
prev=head;
head=temp;
}
return prev;
}