Skip to content

Instantly share code, notes, and snippets.

@Angelfire
Last active January 11, 2023 01:40
Show Gist options
  • Save Angelfire/992eba63a59c5669bcd5f5cd03a89365 to your computer and use it in GitHub Desktop.
Save Angelfire/992eba63a59c5669bcd5f5cd03a89365 to your computer and use it in GitHub Desktop.
Linked List
class LinkedList {
constructor() {
this.head = null
}
addFirst(node) {
if (this.head === null) {
this.head = node
} else {
node.next = this.head
this.head = node
}
}
addLast(node) {
if (this.head === null) {
this.head = node
} else {
let current = this.head
while (current.next !== null) {
current = current.next
}
current.next = node
}
}
indexOf(node) {
let current = this.head
let index = 0
while (current !== null) {
if (current === node) {
return index
}
current = current.next
index += 1
}
return -1
}
removeAt(index) {
if (this.head === null) {
return;
}
if (index === 0) {
this.head = this.head.next;
return;
}
let current = this.head;
let previous;
let i = 0;
while (current !== null && i < index) {
previous = current;
current = current.next;
i++;
}
if (current === null) {
return;
}
previous.next = current.next;
}
}
module.exports = LinkedList;
class Node {
constructor(data) {
this.data = data
this.next = null
}
}
module.exports = Node;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment