输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
//进位
int curr = 0;
ListNode res = new ListNode();
var newNode = res;
while(l1 != null || l2 != null){
int l1val = 0;
int l2val = 0;
if(l1 != null){
l1val = l1.val;
}
if(l2 != null){
l2val = l2.val;
}
var tempVal = l1val + l2val + curr;
curr = tempVal / 10;
var rval = tempVal % 10;
newNode.next = new ListNode(rval);
newNode = newNode.next;
//有的话则取
l1 = l1?.next;
l2 = l2?.next;
}
// 最后的进位
if(curr != 0){
newNode.next = new ListNode(1);
}
return res.next;
}
}