Created
October 20, 2021 09:49
-
-
Save harshvats2000/2fa8406bcf569e62543504f621a87904 to your computer and use it in GitHub Desktop.
Linked List and it's methods implementations using class in 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
// SINGLY LINKED LIST | |
class SinglyLinkedList { | |
constructor(head = null) { | |
this.head = head; | |
} | |
getFirstNode() { | |
return this.head; | |
} | |
addAtHead(val) { | |
let node = { | |
val, | |
next: this.head, | |
}; | |
this.head = node; | |
} | |
getLastNode() { | |
let lastNode = this.head; | |
if (this.head !== null) { | |
while (lastNode.next !== null) { | |
lastNode = lastNode.next; | |
} | |
} | |
return lastNode; | |
} | |
addAtTail(val) { | |
let node = { | |
val, | |
next: null, | |
}; | |
if (this.head === null) { | |
this.head = node; | |
return; | |
} | |
let lastNode = this.getLastNode(); | |
lastNode.next = node; | |
} | |
getNodeAtIndex(index) { | |
let node = this.head; | |
for (let i = 0; i < index; i++) { | |
if (node) { | |
node = node.next; | |
} | |
} | |
return node; | |
} | |
addAtIndex(index, val) { | |
if (index === 0) { | |
this.addAtHead(val); | |
return; | |
} | |
let node = { | |
val, | |
next: this.getNodeAtIndex(index), | |
}; | |
let prevNode = this.getNodeAtIndex(index - 1); | |
if (prevNode) { | |
prevNode.next = node; | |
} | |
} | |
deleteFirstNode() { | |
this.head = this.head.next; | |
} | |
deleteLastNode() { | |
if (this.head === null) { | |
return; | |
} | |
let secondLastNode = this.head; | |
while (secondLastNode.next !== this.getLastNode()) { | |
secondLastNode = secondLastNode.next; | |
} | |
secondLastNode.next = null; | |
} | |
getValue(index) { | |
let node = this.getNodeAtIndex(index); | |
return node ? node.val : -1; | |
} | |
deleteAtIndex(index) { | |
if (index === 0) { | |
this.deleteFirstNode(); | |
} | |
let prevNode = this.getNodeAtIndex(index - 1); | |
let nextNode = this.getNodeAtIndex(index + 1); | |
if (prevNode) { | |
prevNode.next = nextNode; | |
} | |
} | |
} | |
let list = new SinglyLinkedList(); | |
list.addAtHead(1); // 1 | |
list.addAtHead(2); // 2, 1 | |
list.addAtTail(3); // 2, 1, 3 | |
console.log(JSON.stringify(list)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment