forked from realpacific/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSumLists.kt
38 lines (34 loc) · 871 Bytes
/
SumLists.kt
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
package linkedlists
fun main() {
val list1 = LinkedList()
// 617
list1.addLast(Node(7))
list1.addLast(Node(1))
list1.addLast(Node(6))
// 295
val list2 = with(LinkedList()) {
addLast(Node(5))
addLast(Node(9))
addLast(Node(2))
this
}
val result = LinkedList()
addNode(list1.node, list2.node, carry = 0, result = result)
result.printAll()
}
fun addNode(node1: Node?, node2: Node?, carry: Int, result: LinkedList) {
if (node1 == null && node2 == null && carry == 0) {
return
}
var value = carry
if (node1 != null) {
value += node1.value
}
if (node2 != null) {
value += node2.value
}
val newNodeValue = value % 10
val newCarry = value / 10
result.addLast(Node(newNodeValue))
addNode(node1?.next, node2?.next, newCarry, result)
}