要注意两个链表的长度不同,也可能发生连续进位的情况,比如,1->9->9 和 9
长度不同时把短的链表的值当成0,再用一个整数保存进位,这样当长链表走完时,如果进位还有值就要新建一个节点接上去
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode node = new ListNode(0);
ListNode cur = node;
int head = 0;
while (l1 != null || l2 != null){
int first = l1 == null ? 0 : l1.val;
int second = l2 == null ? 0 : l2.val;
int value = first + second + head;
head = value / 10;
ListNode next = new ListNode(value % 10);
cur.next = next;
if (l1 != null){
l1 = l1.next;
}
if (l2 != null){
l2 = l2.next;
}
cur = next;
}
if (head > 0){
cur.next = new ListNode(head);
}
return node.next;
}