/**
* 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) {
ListNode res = new ListNode(0);
ListNode tempNode;
ListNode shift = res;//用shift来代替res移位
int temp = 0;
int carry = 0;
//共同的位
while(l1 != null && l2 != null){
temp = (l1.val + l2.val + carry) % 10;
carry = (l1.val + l2.val + carry) / 10;
tempNode = new ListNode(temp);
shift.next = tempNode;//返回结果时记得将res右移一位
shift = tempNode;
l1 = l1.next;//记得将l1与l2往后移
l2 = l2.next;
}
//位数不同的处理
while(l1 != null){
temp = (l1.val + carry) % 10;
carry = (l1.val + carry) / 10;
tempNode = new ListNode(temp);
shift.next = tempNode;
shift = tempNode;
l1 = l1.next;//记得将l1往后移
}
while(l2 != null){
temp = (l2.val + carry) % 10;
carry = (l2.val + carry) / 10;
tempNode = new ListNode(temp);
shift.next = tempNode;
shift = tempNode;
l2 = l2.next;//记得将l2往后移
}
//处理额外的进位
if(carry != 0){
tempNode = new ListNode(carry);//是carry不是temp
shift.next = tempNode;
}
res = res.next;
return res;
}
}
同样的方法,更简洁的代码
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode c1 = l1;
ListNode c2 = l2;
ListNode sentinel = new ListNode(0);
ListNode d = sentinel;
int sum = 0;
while (c1 != null || c2 != null) {
sum /= 10;
if (c1 != null) {
sum += c1.val;
c1 = c1.next;
}
if (c2 != null) {
sum += c2.val;
c2 = c2.next;
}
d.next = new ListNode(sum % 10);
d = d.next;
}
if (sum / 10 == 1)
d.next = new ListNode(1);
return sentinel.next;
}
}