题目描述:
想法:
逐位相加即可
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dumpnode = new ListNode(0, null);
ListNode temp = dumpnode;
int a = 0, b = 0, r = 0;
while(l1 != null || l2 != null){
a = l1 != null ? l1.val : 0;
b = l2 != null ? l2.val : 0;
ListNode newNode = new ListNode((a + b + r) % 10, null);
temp.next = newNode;
temp = temp.next;
r = (a + b + r) / 10;
if(l1 != null) l1 = l1.next;
if(l2 != null) l2 = l2.next;
}
if(r != 0){
ListNode newNode = new ListNode(1);
temp.next = newNode;
}
return dumpnode.next;
}
}