/**
- 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 head = new ListNode();
ListNode result = head;
boolean equalTen = false;
//需要考虑l1比l2长,或者l2比l1长
while(l1 != null || l2 != null){
result.next = new ListNode();
result = result.next;
if(l1 != null && l2 == null){
result.val = l1.val;
}else if(l1 == null && l2 != null){
result.val = l2.val;
}
else{
result.val = l1.val + l2.val;
}
if(equalTen){
result.val += 1;
}
if(result.val >= 10){
equalTen = true;
result.val -= 10;
}else{
equalTen = false;
}
if(l1!=null){
l1=l1.next;
}
if(l2!=null){
l2=l2.next;
}
}
//需要考虑最后一位相加大于9的情况
if(equalTen){
result.next = new ListNode();
result = result.next;
result.val = 1;
}
return head.next;
}
}