该题直接模拟加法过程。每个node的值是一个单一的数字,且没有前置0,条件设置相对简单,直接扫描两个链表即可。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null||l2 == null){
return null;
}
int carry = 0, sum = 0;
ListNode retNode = new ListNode(0);
ListNode node = retNode;
while (l1 != null&&l2 != null){
sum = l1.val + l2.val + carry;
ListNode tmpNode = new ListNode(sum%10);
carry = sum/10;
node.next = tmpNode;
node = node.next;
l1 = l1.next;
l2 = l2.next;
}
while (l1 != null){
sum = l1.val + carry;
ListNode tmpNode = new ListNode(sum%10);
carry = sum/10;
node.next = tmpNode;
node = node.next;
l1 = l1.next;
}
while (l2 != null){
sum = l2.val + carry;
ListNode tmpNode = new ListNode(sum%10);
carry = sum/10;
node.next = tmpNode;
node = node.next;
l2 = l2.next;
}
if (carry != 0){
ListNode tmpNode = new ListNode(carry);
node.next = tmpNode;
}
return retNode.next;
}
}