-
Notifications
You must be signed in to change notification settings - Fork 0
/
createLinkedList.mjs
135 lines (104 loc) · 2.73 KB
/
createLinkedList.mjs
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import createNode from "./createNode.mjs";
export default function createLinkedList() {
let headNode = null;
const head = () => headNode;
const tail = () => {
if (headNode === null) return null; // empty linked list
let currentNode = headNode;
while (currentNode.nextNode !== null) {
currentNode = currentNode.nextNode;
}
return currentNode;
};
const size = () => {
let count = 0;
if (headNode === null) return count;
let currentNode = headNode;
while (currentNode) {
count++;
currentNode = currentNode.nextNode;
}
return count;
};
/* finders */
const at = (idx) => {
const length = size();
if (length === 0) return null;
if (idx < 0) idx = length + idx;
if (idx >= length || idx < 0) {
console.error("Given index is out of range.");
return null;
}
let currentNode = headNode;
for (let i = 0; i < idx; i++) currentNode = currentNode.nextNode;
return currentNode;
};
const find = (value) => {
if (headNode === null) return null;
let idx = 0;
let currentNode = headNode;
while (currentNode) {
if (currentNode.value === value) return idx;
currentNode = currentNode.nextNode;
idx++;
}
return null;
};
const contains = (value) => {
if (headNode === null) return false;
let currentNode = headNode;
while (currentNode) {
if (currentNode.value === value) return true;
currentNode = currentNode.nextNode;
}
return false;
};
/* manipulation methods */
const prepend = (value) => {
const newNode = createNode(value);
// if list is non-empty
if (headNode !== null) newNode.nextNode = headNode;
headNode = newNode;
};
const append = (value) => {
const newNode = createNode(value);
// if list is empty, new node is head
if (headNode === null) return (headNode = newNode);
const tailNode = tail();
tailNode.nextNode = newNode;
};
const pop = () => {
const length = size();
if (length === 0) return console.log("Linked list is already empty.");
if (length === 1) return (headNode = null);
let currentNode = headNode;
while (currentNode.nextNode.nextNode) {
currentNode = currentNode.nextNode;
}
currentNode.nextNode = null;
};
/* printing */
const toString = () => {
let res = "";
if (headNode === null) return "null"; // empty linkedList
// traversing
let currentNode = headNode;
while (currentNode) {
res += `( ${currentNode.value} ) -> `;
currentNode = currentNode.nextNode;
}
return (res += `${currentNode}`);
};
return {
size,
head,
tail,
append,
prepend,
at,
pop,
find,
contains,
toString,
};
}