0%

2. 两数相加

题目

有问题的解法1

代码

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
54
55
56
57
58
59
60
61
/**
* 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) {
int nextNodeCarryValue = 0;
ListNode sum = new ListNode(nextNodeCarryValue);
ListNode s = sum;

ListNode t1 = l1, t2 = l2;
int a = 0;
int b = 0;

while(t1 != null || t2 != null){
// 计算和
int res = t1.val + t2.val;

int nodeValue = res % 10;
nextNodeCarryValue = res / 10;

// 先创建下一个结点
ListNode nextNode = new ListNode(nextNodeCarryValue);

s.val += nodeValue;

// 移动结点
t1 = t1.next;
t2 = t2.next;

// 顺便处理最后一个结点,这里的代码十分难理解
if((t1 != null || t2 != null) || nextNodeCarryValue != 0){
s.next = nextNode;
s = s.next;
}
}

// 进最后一位
// if(nextNodeCarryValue != 0){
// s.next = new ListNode(nextNodeCarryValue);
// }

//处理两个 ListNode 不等长的情况
ListNode t = null;
if(t1 != null){
t = t1;
}
else{
t =t2;
}
while(t != null){
s.next = new ListNode(t.val);
t = t.next;
}
return sum;
}
}