Problem:
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.
/**
* 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 ln=new ListNode(0);
if(l1==null&&l2==null) return null;
else if(l1==null) return l2;
else if(l2==null) return l1;
else if(l1.next==null&&l2.next==null){
ln.val=l1.val+l2.val;
if(ln.val>9){
int temp=ln.val%10;
ln.next=new ListNode(ln.val/10);
ln.val=temp;
}
return ln;
}
else if(l1.next==null){
ln.val=l1.val+l2.val;
l2.val=0;
if(ln.val>9){
int temp=ln.val%10;
ln.next=new ListNode(ln.val/10);
ln.val=temp;
}
ln.next=addTwoNumbers(ln.next,l2.next);
return ln;
}
else if(l2.next==null){
ln.val=l1.val+l2.val;
l1.val=0;
if(ln.val>9){
int temp=ln.val%10;
ln.next=new ListNode(ln.val/10);
ln.val=temp;
}
ln.next=addTwoNumbers(ln.next,l1.next);
return ln;
}
else{
ln.val=l1.val+l2.val;
l1.val=0;
l2.val=0;
if(ln.val>9){
int temp=ln.val%10;
l1.next.val+=ln.val/10;
ln.val=temp;
}
ln.next=addTwoNumbers(l1.next,l2.next);
return ln;
}
}
}