-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Solution.java
50 lines (45 loc) · 1.4 KB
/
Solution.java
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
package 链表操作.q2_两数相加;
/**
* 两次遍历
* 第一次遍历:两个链表对应每个节点分别取和,若含有空节点则空节点取0,产生一个新链表。
* 第二次遍历:对取完和的新链表遍历,判断当前的val是否大于等于10,大于或等于则其自身-10其next加1,若next为空则新建0节点。
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode rs = new ListNode(l1.val + l2.val);
l1 = l1.next;
l2 = l2.next;
ListNode temp = rs;
while (l1 != null || l2 != null) {
int a = 0;
int b = 0;
if (l1 != null) {
a = l1.val;
}
if (l2 != null) {
b = l2.val;
}
int t = a + b;
temp.next = new ListNode(t);
temp = temp.next;
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
temp = rs;
while (temp != null) {
if (temp.val >= 10) {
temp.val = temp.val - 10;
if (temp.next == null) {
temp.next = new ListNode(0);
}
temp.next.val = temp.next.val + 1;
}
temp = temp.next;
}
return rs;
}
}