Last active
February 19, 2024 18:51
-
-
Save tdubs42/52f38b103e85540b6d57112db2135415 to your computer and use it in GitHub Desktop.
Linked List Class - JavaScript
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
const Node = require('./Node'); | |
class LinkedList { | |
constructor() { | |
this.head = null; | |
} | |
addToHead(data) { | |
const newHead = new Node(data); | |
const currentHead = this.head; | |
this.head = newHead; | |
if (currentHead) { | |
this.head.setNextNode(currentHead); | |
} | |
} | |
addToTail(data) { | |
let tail = this.head; | |
if (!tail) { | |
this.head = new Node(data); | |
} else { | |
while (tail.getNextNode() !== null) { | |
tail = tail.getNextNode(); | |
} | |
tail.setNextNode(new Node(data)); | |
} | |
} | |
removeHead() { | |
const removedHead = this.head; | |
if (!removedHead) { | |
return; | |
} | |
if (removedHead.next) { | |
this.head = removedHead.getNextNode(); | |
} | |
return removedHead.data; | |
} | |
printList() { | |
let currentNode = this.head; | |
let output = '<head> '; | |
while (currentNode !== null) { | |
output += currentNode.data + ' '; | |
currentNode = currentNode.getNextNode(); | |
} | |
output += `<tail>`; | |
console.log(output); | |
} | |
findNodeIteratively(data) { | |
let currentNode = this.head; | |
while (currentNode !== null) { | |
if (currentNode.data === data) { | |
return currentNode; | |
} | |
currentNode = currentNode.getNextNode(); | |
} | |
return null; | |
} | |
findNodeRecursively(data, currentNode = this.head) { | |
if (currentNode === null) { | |
return null; | |
} else if (currentNode.data === data) { | |
return currentNode; | |
} else { | |
return this.findNodeRecursively(data, currentNode.getNextNode()); | |
} | |
} | |
} | |
module.exports = LinkedList; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment