两数相加

leetcode: 两数相加

对于链表长度头部未知的,可在头部前多设一个节点来快速获取

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
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode temList1,temList2,newList,newTemList;
temList1 = l1;
temList2 = l2;
int carryBit = 0, newBit = 0;
newList = new ListNode(0);
newTemList = newList;
while(true){
if(temList1 == null){
while(temList2 != null){
newBit = temList2.val + carryBit;
if(newBit > 9){
carryBit = 1;
newBit = newBit - 10;
}else{
carryBit = 0;
}
newTemList.next = new ListNode(newBit);
newTemList = newTemList.next;
temList2 = temList2.next;
}
break;
}
if(temList2 == null){
while(temList1 != null){
newBit = temList1.val + carryBit;
if(newBit > 9){
carryBit = 1;
newBit = newBit - 10;
}else{
carryBit = 0;
}
newTemList.next = new ListNode(newBit);
newTemList = newTemList.next;
temList1 = temList1.next;
}
break;
}
newBit = temList1.val + temList2.val + carryBit;
if(newBit > 9){
carryBit = 1;
newBit = newBit - 10;
}
else{
carryBit = 0;
}
newTemList.next = new ListNode(newBit);
newTemList = newTemList.next;
temList1 = temList1.next;
temList2 = temList2.next;
}
if(carryBit == 1){
newTemList.next = new ListNode(1);
}
return newList.next;
}

}