Node Class
class Node {
constructor(data, next) {
this.data = data;
this.next = next;
}
}
Linked List Initial Setup
class LinkedList {
constructor() {
this.head = null;
this.length = 0;
}
}
Adding a new Node to Start
unshift(data) {
const newHead = new Node(data, this.head);
this.length++;
this.head = newHead;
}
Getting First Node (Head)
getFirst() {
return this.head;
}
Getting Last Node (Tail)
getLast() {
let currentNode = this.head;
while (currentNode && currentNode.next) {
currentNode = currentNode.next;
}
return currentNode;
}
Clear Linked List
clear() {
this.head = null;
this.length = 0;
}
Removing and Returning First Node
shift() {
if (!this.head) {
return;
}
const oldHead = this.head;
this.head = this.head.next;
this.length--;
return oldHead;
}
Removing and Returning Last Node
pop() {
if (!this.head) {
return;
}
if (this.length === 1) {
return this.shift();
}
const last = this.getLast();
let current = this.head;
while (current.next !== last) {
current = current.next;
}
current.next = null;
this.length--;
return last;
}
Adding a new Node to End
push(data) {
if (!this.head) {
return this.unshift(data);
}
const last = this.getLast();
last.next = new Node(data, null);
this.length++;
}
Return Node at given Index
get(index) {
if (index >= this.length || index < 0) {
return null;
}
let counter = 0;
let current = this.head;
while (counter < index) {
current = current.next;
counter++;
}
return current;
}
Update Node at given Index
set(index, data) {
if (!this.get(index)) {
return false;
}
const node = this.get(index);
node.data = data;
return true;
}
Remove Node at given Index
remove(index) {
if (!this.get(index)) {
return;
}
if (index === 0) {
return this.shift();
}
const nodeToRemove = this.get(index);
const prevNode = this.get(index - 1);
prevNode.next = prevNode.next.next;
this.length--;
return nodeToRemove;
}
Insert a new Node at given Index
insert(index, data) {
if (index >= this.length || index < 0) {
return false;
}
if (index === 0) {
this.unshift(data);
return true;
}
const prevNode = this.get(index - 1);
const nextNode = this.get(index);
prevNode.next = new Node(data, nextNode);
this.length++;
return true;
}