题目要求:
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
大致就是倒序求俩个链表的和值,如有进位则加到下一个。返回一个结果链表。
思路就是遍历一遍L1,L2依次对每项求和,然后把结果依次放到自己创建的链表对应node中,最后返回创建的链表。
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null && l2 == null) {
return null;
}
ListNode lHead;
ListNode temp = new ListNode(0);
lHead = temp;
int flag = 0;
while (l1 != null || l2 != null) {
ListNode lnext = new ListNode(0);
int a = l1==null ? 0 : l1.val;
int b = l2==null ? 0 : l2.val;
lnext.val = (a+b+flag) % 10;
flag = (a+b+flag) / 10;
temp.next = lnext;
temp = temp.next;
l1 = l1==null?null:l1.next;
l2 = l2==null?null:l2.next;
}
if(flag != 0) {
ListNode lnext = new ListNode(0);
lnext.val = flag;
temp.next = lnext;
}
return lHead.next;
}
题目本身不难,这里想说一点就是:对象A=对象B,其实是把B的地址赋值给A,之后B再引用其他地址(eg:B=C),那么A的值是不受影响的,A引用的还是之前的地址的值。