Linked List Implementation with Javascript
Aug 8, 2022Arkar Kaung Myat
Javascript
Simple linked list implementation with javascript.
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
let countNodes = (node) => {
let count = 0;
let head = node;
while (head.next !== null) {
head = head.next;
count = count + 1;
}
return count;
};
let pushFront = (ele, list) => {
let newNode = new Node(ele);
newNode.next = list;
return newNode;
};
let pushAtElement = (newEle, target, list) => {
let head = list;
let prev;
let newNode = new Node(newEle);
while (head.next !== null) {
if (head.val === target) {
prev = head;
break;
}
head = head.next;
}
newNode.next = prev.next;
prev.next = newNode;
return list;
};
let pushAtEnd = (newEle, list) => {
let newNode = new Node(newEle);
if (list === null) {
list = newNode;
return list;
}
let head = list;
let prev;
while (head.next !== null) {
prev = head;
head = head.next;
}
newNode.next = prev.next;
prev.next = newNode;
};
let deleteAtFront = (list) => {
let tmp = list;
list = tmp.next;
return list;
};
let deleteAtEnd = (list) => {
let head = list;
let prev;
while (head.next !== null) {
prev = head;
head = head.next;
}
prev.next = null;
return list;
};
let deleteAtElement = (ele, list) => {
let prev;
let head = list;
while (head.next !== null) {
if (head.val === ele) {
prev = head;
if (prev.next) {
let rest = prev.next.next;
prev.next = rest;
} else {
prev.next = null;
}
break;
}
head = head.next;
}
return list;
};