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
本道题就是考查的是链表的操作,此处有两个注意点:
对链表1和链表2中的每个元素相加,取模(%)放入result链表中,除(/)放入add变量中,最终需要考虑是否add中还有值,这是进位。
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l1_r = l1;
ListNode l2_r = l2;
ListNode result = null;// 作为返回值
// 处理第一个结点
int add = 0;// 进位
int s = l1_r.val + l2_r.val + add;
result = new ListNode(s % 10);
add = s / 10;
l1_r = l1_r.next;
l2_r = l2_r.next;
//上面的result作为头结点的指针
ListNode l3_r = result;//l3_r作为链表的指针遍历
while (l1_r != null || l2_r != null) {
// 同时都不为null
ListNode l3 = null;
int sum = 0;
if (l1_r != null && l2_r != null) {
sum = l1_r.val + l2_r.val + add;
l3 = new ListNode(sum % 10);
add = sum / 10;
// 后移
l1_r = l1_r.next;
l2_r = l2_r.next;
} else if (l1_r != null && l2_r == null) {
sum = l1_r.val + add;
l3 = new ListNode(sum % 10);
add = sum / 10;
// 后移
l1_r = l1_r.next;
} else {
sum = l2_r.val + add;
l3 = new ListNode(sum % 10);
add = sum / 10;
// 后移
l2_r = l2_r.next;
}
l3_r.next = l3;
l3_r = l3_r.next;
}
//判断最后的add
/**
* 最后会有一种情况就是链表的计算都结束了,但是add中还有进位,此时要注意的是计算进位
*/
if (add != 0){
ListNode last = new ListNode(add);
l3_r.next = last;
}
return result;
}