You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
做这种指针指向位置的值会变的题有一个很重要的方法就是设置一个carry变量,当前一个指针指向的操作会影响到下一个节点时,carry也会随之改变,因此也就能作为改变的参照。这道题可以说是一道很典型的这类题目,因为要考虑是否相加会超过10,所以用carry来记录。当大于10的时候只需要把carry更新为1,既(l1.val+l2.val)/10即可。然后下一个节点只需要l1.val+l2.val+carry即可。这道题只给了一个case我觉得不好很有误导性,因为这两个list长度一样,其实我们还要考虑长度不一样,这样情况就需要我们在加完之后再进行单个list的指针遍历。
做的过程中用到了dummy.node来做,这样的话就能保证最后返回dummy.next就行
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null && l2 == null) {
return null;
}
int digit = 0;
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
while(l1!=null&&l2!=null){
int sum = digit+l1.val+l2.val;
cur.next=new ListNode(sum%10);
digit=sum/10;
cur=cur.next;
l1=l1.next;
l2=l2.next;
}
while(l1!=null){
int sum = digit+l1.val;
cur.next=new ListNode(sum%10);
digit=sum/10;
cur=cur.next;
l1=l1.next;
}
while(l2!=null){
int sum = digit+l2.val;
cur.next=new ListNode(sum%10);
digit=sum/10;
cur=cur.next;
l2=l2.next;
}
<span style="white-space:pre"> </span>//要考虑最后万一carry还大于0时,我们还需要增加一个节点,也就是极端情况
if(digit!=0){
cur.next=new ListNode(digit);
}
return dummy.next;
}
}