Leetcode-2. 两数相加

LeetCode链表问题:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 两个已知链表对象ListNode l1, ListNode l2
输出:7 -> 0 -> 8
原因:342 + 465 = 807

1
2
3
graph LR
1((2)) --> 2((4)) --> 3((3))
4((5))--> 5((6)) --> 6((4))

1
2
graph LR
7((7)) --> 8((0)) --> 9((7))

备注:一开始是真没看懂题目。。。后来发现是反向存储的链表结构,又发现不知道ListNode这个类,,万事开头难,看着大家的方案题解,也琢磨了一份,并给出了详细的注释,算是留个笔记吧,继续努力!

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* 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) {
//记录结果,用于最后返回
ListNode root = new ListNode();
//存储过程中的游标
ListNode cursor = root;
//保存进位
int carry = 0;

//计算共同长度的部分
while(l1 != null && l2 != null){
int sumVal = l1.val + l2.val + carry;
cursor.next = new ListNode(sumVal % 10);
//计算进位
carry = sumVal / 10;

//下一节点
l1 = l1.next;
l2 = l2.next;
cursor = cursor.next;
}

//根据剩余长度构建存储节点
ListNode overplus = null;
overplus = l1 != null ? l1 : l2;

while(overplus != null){
int sumVal = overplus.val + carry;
cursor.next = new ListNode(sumVal % 10);
//计算进位
carry = sumVal / 10;

//下一节点
overplus = overplus.next;
cursor = cursor.next;
}

//判断是否有进位残留
if(carry != 0){
cursor.next = new ListNode(carry);
}

return root.next;
}
}