-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathsumLists - forward.js
More file actions
84 lines (69 loc) · 1.79 KB
/
sumLists - forward.js
File metadata and controls
84 lines (69 loc) · 1.79 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
83
84
const LinkedList = require('./../util/LinkedList')
const printList = require('./../util/printList')
function sumLinkedListsForward(list1, list2) {
if (!list1 && !list2) {
return null
}
let length1 = length(list1)
let length2 = length(list2)
if (length1 > length2) {
list2 = padList(list2, length1 - length2)
} else if (length1 < length2) {
list1 = padList(list1, length2 - length1)
}
const { head, nextDigitValue } = carryBase10(sumAndAppendNodes(list1, list2), 0)
return nextDigitValue ? appendToStart(head, new LinkedList(nextDigitValue)) : head
}
function length(node) {
let count = 0
while (node) {
count++
node = node.next
}
return count
}
function padList(shortList, padding) {
while (padding > 0) {
shortList = appendToStart(shortList, new LinkedList(0))
padding--
}
return shortList
}
function appendToStart(head, node) {
node.next = head
return node
}
function sumAndAppendNodes(node1, node2) {
let value = (node1 ? node1.value : 0) + (node2 ? node2.value : 0)
if (!node1.next && !node2.next) {
return new LinkedList(value)
}
const {
head,
nextDigitValue
} = carryBase10(sumAndAppendNodes(node1.next, node2.next), value)
return appendToStart(head, new LinkedList(nextDigitValue))
}
function carryBase10(head, nextDigitValue) {
if (head.value >= 10) {
head.value = head.value % 10
nextDigitValue += 1
}
return {
head,
nextDigitValue
}
}
// Input: (6 -> 1 -> 7) + (2 -> 9 -> 5). this case refers to 617 + 295
// Output: 9 -> 1 -> 2. the answer refers to 912
var a = new LinkedList(6)
var b = new LinkedList(1)
var c = new LinkedList(7)
a.next = b
b.next = c
var d = new LinkedList(2)
var e = new LinkedList(9)
var f = new LinkedList(5)
d.next = e
e.next = f
printList(sumLinkedListsForward(a, d))