Last active
February 19, 2024 01:30
-
-
Save tdubs42/ef7740e2311e532ffd4cc1e7b48866e2 to your computer and use it in GitHub Desktop.
Doubly 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 DoublyLinkedList { | |
constructor() { | |
this.head = null; | |
this.tail = null; | |
} | |
addToHead(data) { | |
const newHead = new Node(data); | |
const currentHead = this.head; | |
if (currentHead) { | |
currentHead.setPreviousNode(newHead); | |
newHead.setNextNode(currentHead); | |
} | |
this.head = newHead; | |
if (!this.tail) { | |
this.tail = newHead; | |
} | |
} | |
addToTail(data) { | |
const newTail = new Node(data); | |
const currentTail = this.tail; | |
if (currentTail) { | |
currentTail.setNextNode(newTail); | |
newTail.setPreviousNode(currentTail); | |
} | |
this.tail = newTail; | |
if (!this.head) { | |
this.head = newTail; | |
} | |
} | |
removeHead() { | |
const removedHead = this.head; | |
if (!removedHead) { | |
return; | |
} | |
this.head = removedHead.getNextNode(); | |
if (this.head) { | |
this.head.setPreviousNode(null); | |
} | |
if (removedHead === this.tail) { | |
this.removeTail(); | |
} | |
return removedHead.data; | |
} | |
removeTail() { | |
const removedTail = this.tail; | |
if (!removedTail) { | |
return; | |
} | |
this.tail = removedTail.getPreviousNode(); | |
if (this.tail) { | |
this.tail.setNextNode(null); | |
} | |
if (removedTail === this.head) { | |
this.removeHead(); | |
} | |
return removedTail.data; | |
} | |
removeByData(data) { | |
let nodeToRemove; | |
let currentNode = this.head; | |
while (currentNode !== null) { | |
if (currentNode.data === data) { | |
nodeToRemove = currentNode; | |
break; | |
} | |
currentNode = currentNode.getNextNode(); | |
} | |
if (!nodeToRemove) { | |
return null; | |
} | |
if (nodeToRemove === this.head) { | |
this.removeHead(); | |
} else if (nodeToRemove === this.tail) { | |
this.removeTail(); | |
} else { | |
const nextNode = nodeToRemove.getNextNode(); | |
const previousNode = nodeToRemove.getPreviousNode(); | |
nextNode.setPreviousNode(previousNode); | |
previousNode.setNextNode(nextNode); | |
} | |
return nodeToRemove; | |
} | |
printList() { | |
let currentNode = this.head; | |
let output = '<head> '; | |
while (currentNode !== null) { | |
output += currentNode.data + ' '; | |
currentNode = currentNode.getNextNode(); | |
} | |
output += '<tail>'; | |
console.log(output); | |
} | |
} | |
const subway = new DoublyLinkedList() | |
module.exports = DoublyLinkedList; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment