- First, Let's see the description of second problem in leetcode:
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
Second, let's analyze the problem:
1.From head to tail, the list is a number from low to high
2.If the sum of two number is larger than 10, its higher position will add one
3.If the sum in the highest position is larger than 10, the length of list will add
4.If one input list is null, the result is another list.Third, my solution:
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode help=new ListNode(0);
ListNode stay=help;
int carry=0;
if(l1==null && l2==null) return null;
while(l1!=null || l2!=null || carry!=0){
ListNode temp = new ListNode(0);
int sum = ((l1==null)?0:l1.val)+((l2==null)?0:l2.val)+carry;
temp.val=sum%10;
help.next=temp;
carry=sum/10;
help=temp;
if(l1!=null) l1=l1.next;
if(l2!=null) l2=l2.next;
}
return stay.next;
}
}