forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SinglyLinkedList.js
82 lines (68 loc) · 1.91 KB
/
SinglyLinkedList.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
78
79
80
81
// SinglyListNode represents a node in a singly linked list.
class SinglyListNode {
constructor(value, next) {
this.value = value;
this.next = next;
}
}
// SinglyLinkedList represents a singly linked list data structure.
class SinglyLinkedList {
constructor() {
this.head = null;
this.tail = null;
}
addToFront(value) {
let newNode = new SinglyListNode(value, this.head);
if (this.head === null) {
this.head = newNode;
this.tail = newNode;
} else {
this.head = newNode;
}
}
addToEnd(value) {
let newNode = new SinglyListNode(value, null);
if (this.head === null) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
}
remove(value) {
if (this.head === null) {
return;
}
if (this.head.value === value) {
this.head = this.head.next;
} else {
let currentNode = this.head;
let nodeToDelete = null;
while (currentNode.next !== null) {
if (currentNode.next.value === value) {
nodeToDelete = currentNode.next;
currentNode.next = currentNode.next.next;
break;
}
currentNode = currentNode.next;
}
if (nodeToDelete === null) {
console.log("Value not found");
}
}
}
read() {
if (this.head === null) {
console.log("Empty");
return;
}
let currentNode = this.head;
console.log("Listing");
while (currentNode !== null) {
console.log(currentNode.value);
currentNode = currentNode.next;
}
}
}
module.exports = SinglyLinkedList;