-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked-list-sum-list.js
60 lines (46 loc) · 924 Bytes
/
linked-list-sum-list.js
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
/*
sum list
Write a function, sumList, that takes in the head of a linked list containing numbers as an argument. The function should return the total sum of all values in the linked list.
test_00:
const a = new Node(2);
const b = new Node(8);
const c = new Node(3);
const d = new Node(-1);
const e = new Node(7);
a.next = b;
b.next = c;
c.next = d;
d.next = e;
// 2 -> 8 -> 3 -> -1 -> 7
sumList(a); // 19
test_01:
const x = new Node(38);
const y = new Node(4);
x.next = y;
// 38 -> 4
sumList(x); // 42
test_02:
const z = new Node(100);
// 100
sumList(z); // 100
test_03:
sumList(null); // 0
*/
// class Node {
// constructor(val) {
// this.val = val;
// this.next = null;
// }
// }
const sumList = (head) => {
let totalSum = 0;
let current = head;
while (current !== null) {
totalSum += current.val;
current = current.next;
}
return totalSum;
};
module.exports = {
sumList
};