-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedList.js
More file actions
60 lines (55 loc) · 1.23 KB
/
linkedList.js
File metadata and controls
60 lines (55 loc) · 1.23 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
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor(value) {
this.head = {
value,
next: null,
};
this.tail = this.head;
this.length = 1;
}
append(value) {
const newNode = new Node(value);
this.tail.next = newNode;
this.tail = newNode;
this.length++;
return this;
}
prepend(value) {
const newNode = new Node(value);
newNode.next = this.head;
this.head = newNode;
this.length++;
return this;
}
printList() {
const array = [];
let currentNode = this.head;
while (currentNode !== null) {
array.push(currentNode.value);
currentNode = currentNode.next;
}
return array;
}
insert(index, value) {
let currentIndex = 0;
let objHead = this.head;
while (currentIndex < index && objHead !== null) {
objHead = objHead.next;
currentIndex++;
}
let newItem = { value: value, next: objHead };
return console.log(currentIndex, newItem);
}
}
const myLinkedList = new LinkedList("Chicken");
myLinkedList.append("yogurt");
myLinkedList.append("Fish");
myLinkedList.prepend("Beef");
myLinkedList.insert(2, "bread");
console.log(myLinkedList.printList());