思路

按照链表的顺序去取出val 进行相加 如果链表长度不同则后补0
相加后进行进位判断

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* 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) {

//不够长后补0
ListNode res=new ListNode(0);
ListNode res_next=res;
int carry=0;
while(l1!=null||l2!=null){

int a=l1==null?0:l1.val;
int b=l2==null?0:l2.val;

int r=a+b+carry;
carry=r/10;
r=r%10;
res_next.next=new ListNode(r);
res_next=res_next.next;
if(l1!=null)
l1=l1.next;
if(l2!=null)
l2=l2.next;

}
if(carry==1)
res_next.next=new ListNode(carry);
return res.next;
}
}

作者声明

1
如有问题,欢迎指正!