-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedlist.js
77 lines (70 loc) · 1.44 KB
/
linkedlist.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//find the maximum value in a list using linked lists
class Node {
constructor(data) {
this.head = null;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
addNode(data) {
const newNode = new Node(data);
//first check if the list is empty
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
//there is a head
this.tail.next = newNode;
this.tail = newNode;
}
}
removeNode(data) {
//first check if the list is empty
if (!this.head) {
return;
}
//check for the first item
if (this.head.data === data) {
this.head = this.head.next;
}
//loop over the list
let current = this.head;
while (current) {
if (current.data === data) {
current.next = current.next.next;
return;
}
current = current.next;
}
}
//propagating the list
traverse(callback) {
let current = this.head;
while (current) {
callback(current);
current = current.next;
}
}
findMax(node) {
let max = Number.NEGATIVE_INFINITY;
let current = this.head;
while (current) {
if (current.head > max) {
max = current.head;
}
current = current.next;
}
return max;
}
}
const list = new LinkedList();
list.addNode(10);
list.addNode(4);
list.addNode(18);
list.addNode(34);
list.addNode(35);
console.log(list.findMax());