Skip to content

Instantly share code, notes, and snippets.

@jordanrios94
Last active February 3, 2023 02:33
Show Gist options
  • Save jordanrios94/ec6e933dd28f03f63f856265e3688b82 to your computer and use it in GitHub Desktop.
Save jordanrios94/ec6e933dd28f03f63f856265e3688b82 to your computer and use it in GitHub Desktop.
Linked Lists
class LinkedList {
constructor() {
this.head = null;
}
insertFirst(data) {
this.head = new Node(data, this.head);
}
size() {
let counter = 0;
let node = this.head;
while(node) {
counter++;
node = node.next;
}
return counter;
}
getFirst() {
return this.head;
}
getLast() {
if (!this.head) {
return null;
}
let node = this.head;
while(node) {
if (!node.next) {
return node;
}
node = node.next;
}
}
clear() {
this.head = null;
}
removeFirst() {
if (this.head) {
this.head = this.head.next;
}
// this.removeAt(0);
}
removeLast() {
if (!this.head) {
return null;
}
if (!this.head.next) {
this.head = null;
return;
}
let node = this.head.next;
let previousNode = this.head;
while(node.next) {
previousNode = node;
node = node.next;
}
previousNode.next = null;
}
insertLast(data) {
const lastNode = this.getLast();
if (lastNode) {
lastNode.next = new Node(data);
} else {
this.head = new Node(data);
}
}
getAt(index) {
let counter = 0;
let node = this.head;
while(node) {
if (counter === index) {
return node;
}
counter++;
node = node.next;
}
return null;
}
removeAt(index) {
if (!this.head) {
return;
}
if (index === 0) {
this.head = this.head.next;
return;
}
const previousNode = this.getAt(index - 1);
if (!previousNode || !previousNode.next) {
return;
}
previousNode.next = previousNode.next.next;
}
insertAt(data, index) {
if (!this.head) {
this.head = new Node(data);
return;
}
if (index === 0) {
this.head = new Node(data, this.head);
return;
}
const previousNode = this.getAt(index - 1) || this.getLast();
previousNode.next = new Node(data, previousNode.next);
}
forEach(fn) {
let node = this.head;
let counter = 0;
while (node) {
fn(node, counter);
node = node.next;
counter++;
}
}
*[Symbol.iterator]() {
let node = this.head;
while (node) {
yield node;
node = node.next;
}
}
}
class Node {
constructor(data, next = null) {
this.data = data;
this.next = next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment