JSFiddle - React, Tailwind, and code Playground
JavaScript
console.clear();
let c = (...s) => console.log(...s)
// Linked list
function LinkedList() {
let length = 0;
let head = null;
let Node = function(data) {
this.data = data;
this.next = null;
}
// size and head intialization
this.size = () => length;
this.head = () => head;
this.isEmpty = () => (length == 0);
// add new node at end
this.add = (data) => {
let node = new Node(data);
if (head == null) head = node;
else {
let currentNode = head;
while (currentNode.next != null) {
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
// remove(data)
this.remove = (data) => {
if (head.data == data) head = head.next;
else {
let currentNode = head;
let previousNode;
while (currentNode.data != data) {
previousNode = currentNode;
currentNode = currentNode.next;
// if not found at all
if (currentNode == null) return false;
}
// this will remove current node
previousNode.next = currentNode.next;
}
length--;
};
// find index for data
this.indexOf = (data) => {
let currentNode = head;
let index = -1;
while (currentNode) {
index++;
if (currentNode.data == data) return index; // found
currentNode = currentNode.next;
}
return -1; // not found
}
// find data at index
this.dataAt = (index) => {
let currentNode = head;
let count = 0;
while (currentNode) {
if (count == index) return currentNode.data;
count++;
currentNode = currentNode.next;
}
return null; // not found
}
// add(index) in middle
this.addAt = (data, index) => {
let newNode = new Node(data);
let currentNode = head;
let count = 0;
let previousNode;
// invalid index
if (index < 0 || index >= length) return false;
// if index = 0
if (index == 0) {
newNode.next = currentNode;
head =...