首先,要注意有进位的问题,进位的数字下一次计算也会计算,所以就用text来保存进位。在最后结束的时候,如果进位text不为空,还要在链表尾追加一个节点,其值为text。
其次,两个链表的长度不一样,一个链表遍历完了,另一个没遍历完要补0.我这里没有补0节点,而是在计算值的时候用0代替。
代码
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head1 = l1;
ListNode head2 = l2;
ListNode res = new ListNode();
ListNode temp = res;
int text = 0;
while(head1 != null || head2 != null){
ListNode next = new ListNode();
int n1 = head1 != null ? head1.val:0;
int n2 = head2 != null ? head2.val:0;
next.val = ((n1 + n2 + text)%10);
text = (n1 + n2 + text)/10;
if(head1 != null){
head1 = head1.next;
}
if(head2 != null){
head2 = head2.next;
}
temp.next = next;
temp = next;
}
if(text > 0)
temp.next = new ListNode(text);
return res.next;
}
}



