Last active
January 11, 2023 01:40
-
-
Save Angelfire/992eba63a59c5669bcd5f5cd03a89365 to your computer and use it in GitHub Desktop.
Linked List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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