Skip to content

Instantly share code, notes, and snippets.

@TheWebDevel
Created October 31, 2020 11:38
Show Gist options
  • Save TheWebDevel/a69421001e1e1fd94be09115f76219df to your computer and use it in GitHub Desktop.
Save TheWebDevel/a69421001e1e1fd94be09115f76219df to your computer and use it in GitHub Desktop.
Implementation of linked list in Node JS
class Node {
constructor(data, next = null) {
this.data = data;
this.next = next;
}
}
class LinkedList {
constructor() {
this.head = null;
}
size() {
let counter = 0;
let node = this.head;
while (node) {
counter++;
node = node.next;
}
return counter;
}
removeFirst() {
this.head = this.head.next;
}
getFirst() {
return this.getAt(0);
}
getLast() {
return this.getAt(this.size() - 1);
}
clear() {
this.head = null;
}
removeLast() {
this.removeAt(this.size() - 1);
}
insertLast(data) {
let currLast = this.getLast();
if (currLast) {
currLast.next = new Node(data);
} else {
this.insertFirst(data);
}
}
insertFirst(data) {
this.head = new Node(data, this.head);
}
getAt(index) {
let node = this.head;
while (index && node) {
node = node.next;
index--;
}
return node;
}
removeAt(index) {
if (!this.head) return;
if (index === 0) {
this.head = this.head.next;
return;
}
let prevNode = this.getAt(index - 1);
let currNode = this.getAt(index);
if (prevNode) {
prevNode.next = currNode && currNode.next;
}
}
insertAt(data, index) {
if (!this.head || index === 0) {
this.insertFirst(data);
}
let prevNode = this.getAt(index - 1);
let currNode = this.getAt(index);
if (!currNode) {
this.insertLast(data);
}
if (prevNode) {
prevNode.next = new Node(data, currNode);
}
}
forEach(fn) {
let index = 0;
while (index < this.size()) {
let node = this.getAt(index);
fn(node, index);
index++;
}
}
*[Symbol.iterator]() {
let node = this.head;
while (node) {
yield node;
node = node.next;
}
}
}
module.exports = { Node, LinkedList };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment