-
Notifications
You must be signed in to change notification settings - Fork 0
/
2-add2ll.java
75 lines (74 loc) · 2.09 KB
/
2-add2ll.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* 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) {
ListNode ans = new ListNode();
ListNode p1 = l1;
ListNode p2 = l2;
ListNode a1 = ans;
int carry = 0;
if(p1!=null && p2!=null){
a1.val = p1.val + p2.val + carry;
if(a1.val >=10){
a1.val-=10;
carry = 1;
}
p1 = p1.next;
p2 = p2.next;
}
if(a1!=null){
while(p1!=null && p2!=null){
ListNode newnode = new ListNode();
a1.next = newnode;
a1 = a1.next;
a1.val = p1.val + p2.val + carry;
if(a1.val >=10){
a1.val-=10;
carry = 1;
}
else carry = 0;
p1 = p1.next;
p2 = p2.next;
}
while(p1!=null){
ListNode newnode = new ListNode();
a1.next = newnode;
a1 = a1.next;
a1.val = p1.val+carry;
if(a1.val >=10){
a1.val-=10;
carry = 1;
}
else carry = 0;
p1 = p1.next;
}
while(p2!=null){
ListNode newnode = new ListNode();
a1.next = newnode;
a1 = a1.next;
a1.val = p2.val+carry;
if(a1.val >=10){
a1.val-=10;
carry = 1;
}
else carry = 0;
p2 = p2.next;
}
if(carry==1){
ListNode newnode = new ListNode();
a1.next = newnode;
a1 = a1.next;
a1.val = carry;
}
}
return ans;
}
}