JSFiddle - React, Tailwind, and code Playground
by Shridhar Baddur
JavaScript
/* 10 --> 5 --> 16 */
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.length = 0;
this.tail = this.head;
}
size() {
return this.length;
}
isEmpty() {
return this.length === 0 ? true : false;
}
add(value) {
const node = new Node(value);
let current;
if(this.head === null) {
this.head = node;
} else {
current = this.head;
while(current.next) {
current = current.next;
}
current.next = node;
this.tail = current.next;
}
this.length++;
}
printList() {
let current = this.head;
let str = '';
if(current === null)
console.log('The list is empty')
while(current) {
str += current.value;
if(current.next !== null) {
str += ' --> ';
}
current = current.next;
}
console.log(str)
}
valueAt(index) {
if(this.length < index || this.length === 0) {
console.log('The provided index more than length of the list');
return;
}
let current = this.head;
while(index) {
current = current.next
index--;
}
return current.value;
}
pushFront(value) {
const newNode = new Node(value);
newNode.next = this.head;
this.head = newNode;
this.length++;
}
popFront() {
const deletedNode = this.head;
this.head = this.head.next;
this.length--;
return deletedNode;
}
pushBack(value) {
this.add(value);
}
erase(index) {
if(this.length === 0 || this.length < index) {
return console.log('Please provide proper index');
}
let pre = this.head;
for(let i = 0; i < index - 1; i++) {
pre = pre.next;
}
let del = pre.next;
let aft = del.next;
console.log(del);
if(aft === null) {
this.tail = pre;
}
pre.next = aft;
this.length--;
return del;
}
popBack() {
...