-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.js
More file actions
120 lines (80 loc) · 2.17 KB
/
LinkedList.js
File metadata and controls
120 lines (80 loc) · 2.17 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
class Node {
constructor(value) {
this.value = value;
this.previous = null;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
addToHead(value) {
const newNode = new Node(value);
const formerHead = this.head;
this.head = newNode;
if (formerHead) {
formerHead.previous = newNode;
newNode.next = formerHead;
}
if (!this.tail) this.tail = newNode;
}
addToTail(value) {
const newNode = new Node(value);
const formerTail = this.tail;
this.tail = newNode;
if (formerTail) {
formerTail.next = newNode;
newNode.previous = formerTail;
}
if (!this.head) this.head = this.tail;
}
removeHead() {
const removedHead = this.head;
if (!removedHead) return;
if (removedHead.next) {
this.head = removedHead.next;
this.head.previous = null;
} else {
this.head = null;
this.tail = null;
}
return removedHead.value;
}
removeTail() {
const removedTail = this.tail;
if (!removedTail) return;
if (removedTail.previous) {
this.tail = removedTail.previous;
this.tail.next = null;
} else {
this.head = null;
this.tail = null;
}
return removedTail.value;
}
search(comparator) {
let currentNode = this.head;
if (typeof comparator === 'string') {
const comparatorString = comparator;
comparator = function (elementValue) {
return comparatorString === elementValue;
}
}
while (currentNode !== null) {
if (comparator(currentNode.value)) return currentNode.value;
currentNode = currentNode.next;
}
return null;
}
size() {
let i = 0;
let currentNode = this.head;
while (currentNode !== null) {
i++;
currentNode = currentNode.next;
}
return i;
}
}