-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
48 lines (38 loc) · 1.14 KB
/
Copy pathsolution.java
File metadata and controls
48 lines (38 loc) · 1.14 KB
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
class Solution {
private Node reverse(Node head) {
Node prev = null;
while (head != null) {
Node nextNode = head.next;
head.next = prev;
prev = head;
head = nextNode;
}
return prev;
}
public Node addTwoLists(Node head1, Node head2) {
head1 = reverse(head1);
head2 = reverse(head2);
Node dummy = new Node(0);
Node curr = dummy;
int carry = 0;
while (head1 != null || head2 != null || carry != 0) {
int sum = carry;
if (head1 != null) {
sum += head1.data;
head1 = head1.next;
}
if (head2 != null) {
sum += head2.data;
head2 = head2.next;
}
carry = sum / 10;
curr.next = new Node(sum % 10);
curr = curr.next;
}
Node result = reverse(dummy.next);
while (result != null && result.data == 0 && result.next != null) {
result = result.next;
}
return result;
}
}