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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题目解释:两个链表按顺序依次加和,有进位的向后进位,得到结果
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int count = 0;
ListNode result = new ListNode(0);
ListNode p = result;
while(l1 != null||l2 != null){
if( l1 != null){
count += l1.val;
l1 = l1.next;
}
if( l2 != null){
count += l2.val;
l2 = l2.next;
}
ListNode kk = new ListNode(count%10);
p.next = kk;
p = p.next;
count /= 10;
}
if(count!=0){
ListNode n1 = new ListNode(count);
p.next = n1;
}
return result.next;
}
注意的点:
1.定义返回结果result时,需要将result锁住,再指定一个p指向result,p依次向后迭代,最重要的是p = p.next 一定要移动
2.初始写代码时定义了进位符flag,但是会出现没有进位会自动创建一个为0的ListNode会与题意不符,直接创建count%10的ListNode,返回result.next
错误代码:
flag = (result.val + count)/10;
ListNode next = new ListNode(flag);