Singly Linked List
by Varayut Lerdkanlayanawat
JavaScript
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this._length = 0;
}
add(value) {
const node = new Node(value);
if (this.head === null) {
this.head = node;
} else {
// Find the last node
const lastNode = this.getLastNode();
lastNode.next = node;
}
this._length += 1;
return node;
}
getLastNode() {
let currentNode = this.head;
while (currentNode.next) {
currentNode = currentNode.next;
}
return currentNode;
}
searchNodeAt(position) {
// Throw an error if the position doesn't exist
if (position < 0 || position > this._length || this._length === 0) {
throw new Error('Position doesn\'t exist in LinkedList');
}
let count = 1;
let currentNode = this.head;
while (count < position) {
currentNode = currentNode.next;
count += 1;
}
return currentNode;
}
remove(position) {
// Throw an error if the position doesn't exist
if (position < 0 || position > this._length || this._length === 0) {
throw new Error('Position doesn\'t exist in LinkedList');
}
let deletedNode = null;
// In case of deleting head
if (position === 1) {
deletedNode = this.head;
this.head = this.head.next;
} else {
let currentNode = this.head;
let beforeNode = null;
let count = 1;
// Find the previous node before the position
while (count < position) {
beforeNode = currentNode;
currentNode = currentNode.next;
count += 1;
}
beforeNode.next = currentNode.next;
deletedNode = currentNode;
}
this._length -= 1;
return deletedNode;
}
}
const linkedList = new LinkedList();
console.log('-------------add(1),...