Table of contents
Linked Lists
Because Javascript is not an object-oriented language, Javascript does not come with as many data structures as Java or other languages...(Well at least this is my understanding) Because Javascript doesn't have a syntax such as square brackets( [ ] ) for declaring an array, people can code it via classes.
Creating LL(Linked Lists)
Since, Javascript doesn't have a syntax for declaring LL, we have to use brute force to create a structure as shown below.
class Node {
constructor(value) {
this.value = value
this.next = null
}
}
class LinkedList {
constructor(value) {
const newNode = new Node(value)
this.head = newNode
this.tail = this.head
this.length = 1
}
push(value) {
const newNode = new Node(value)
if (!this.head) {
this.head = newNode
this.tail = newNode
} else {
this.tail.next = newNode
this.tail = newNode
}
this.length++
return this //this is referring to this LinkedList
}
}
let myLinkedList = new LinkedList(4)
myLinkedList.push(5)
myLinkedList.push(6)
console.log(myLinkedList)
//LinkedList {
// head: Node { value: 4, next: Node { value: 5, next: [Node] } },
// tail: Node { value: 6, next: null },
// length: 3
LL vs Array
This is a concise comparison between a Linked List and an Array.
I'm not sure how often developers will come across opting to use LL over arrays. However, I'd imagine it would make a world of difference from knowing the data structures.