Last active
March 20, 2021 11:56
-
-
Save DNature/fe9d77564e962414d230f3fad69bd4bd to your computer and use it in GitHub Desktop.
Javascript Linked List algorithm
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
function LinkedList(){ | |
this.length = 0; | |
this.head = null | |
const Node = function(element) { | |
this.element = element | |
this.next = null | |
} | |
this.add = (element) => { | |
const node = new Node(element) | |
if(!this.head){ | |
this.head = node | |
} else { | |
let currentNode = this.head; | |
while(currentNode.next){ | |
currentNode = currentNode.next | |
} | |
currentNode.next = node | |
} | |
this.length++ | |
} | |
this.remove = element => { | |
let currentNode = this.head | |
let previousNode; | |
if(element === currentNode.element){ | |
this.head = currentNode.next | |
} else { | |
while(currentNode.element !== element){ | |
previousNode = currentNode; | |
currentNode = currentNode.next; | |
} | |
previousNode.next = currentNode.next | |
} | |
this.length-- | |
} | |
this.indexOf = element => { | |
let currentNode = this.head | |
let index = -1 | |
while(currentNode){ | |
index++ | |
if(currentNode.element === element){ | |
return index | |
} | |
currentNode = currentNode.next | |
} | |
return -1 | |
} | |
this.removeAt = index => { | |
let currentNode = this.head | |
let currentIndex = 0; // Start at 0 | |
let previousNode; | |
if (index < 0 || index >= this.length){ | |
throw new Error("Invalid index specified") | |
} | |
if(index === 0){ | |
this.head = currentNode.next | |
} else { | |
while(currentIndex < index){ | |
currentIndex++ | |
previousNode = currentNode | |
currentNode = currentNode.next | |
} | |
previousNode.next = currentNode.next | |
} | |
this.length--; | |
return currentNode.element | |
} | |
} | |
const ll = new LinkedList() | |
ll.add(10) | |
ll.add(20) | |
ll.add(20) | |
ll.add(13) | |
ll.removeAt(2) | |
console.log(JSON.stringify(ll.head, null, 2)) | |
console.log(ll.indexOf(13)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment