- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathListNode.java
More file actions
Latest commit
82 lines (71 loc) · 2.18 KB
/
Copy pathListNode.java
File metadata and controls
82 lines (71 loc) · 2.18 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
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
76
77
78
79
80
81
82
packagecom.leetcode;
importorg.junit.jupiter.api.Assertions;
importorg.junit.jupiter.api.Test;
importjava.util.ArrayList;
importjava.util.List;
publicclassListNode {
intval;
ListNodenext;
ListNode() {
}
ListNode(finalintval) {
this.val = val;
}
ListNode(finalintval, finalListNodenext) {
this.val = val;
this.next = next;
}
ListNode(finalint[] nums) {
ListNodedummy_head = newListNode();
ListNodecurr_node = dummy_head;
for (finalvarnum: nums) {
curr_node.next = newListNode(num);
curr_node = curr_node.next;
}
this.val = dummy_head.next.val;
this.next = dummy_head.next.next;
}
int [] to_array() {
List<Integer> numbers = newArrayList<>();
varcurr_node = this;
while (curr_node != null) {
numbers.add(curr_node.val);
curr_node = curr_node.next;
}
returnnumbers.stream().mapToInt(i -> i).toArray();
}
}
classTestListNode {
@Test
voidtest_to_array() {
finalvarnums = newint[] { 1,2,3};
finalvarnode = newListNode(nums);
Assertions.assertArrayEquals(node.to_array(), nums);
}
// https://leetcode.com/problems/add-two-numbers
publicstaticListNodeadd_two_numbers(ListNodel1, ListNodel2) {
ListNodedummyHead = newListNode();
ListNodecurrent_node = dummyHead;
intsumOrCarry = 0;
while (l1 != null || l2 != null || sumOrCarry != 0) {
if (l1 != null) {
sumOrCarry += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sumOrCarry += l2.val;
l2 = l2.next;
}
current_node.next = newListNode(sumOrCarry % 10);
current_node = current_node.next;
sumOrCarry /= 10;
}
returndummyHead.next;
}
@Test
voidtest_add_two_numbers() {
finalListNodeln1 = newListNode(newint[]{5});
finalListNodeln2 = newListNode(newint[]{5});
Assertions.assertArrayEquals(add_two_numbers(ln1, ln2).to_array(), newint[]{0, 1});
}
}