Skip to content

Instantly share code, notes, and snippets.

@Ivanshamir
Created April 6, 2023 19:09
Show Gist options
  • Select an option

  • Save Ivanshamir/d0f56e411edf66a8479e2ecddb2c046e to your computer and use it in GitHub Desktop.

Select an option

Save Ivanshamir/d0f56e411edf66a8479e2ecddb2c046e to your computer and use it in GitHub Desktop.
Implement deque using linked list in js
class Node {
constructor(value) {
this.value = value;
this.next = null;
this.previous = null;
}
}
class Deque {
constructor() {
this.head = null;
this.tail = null;
this.size = 0;
}
addToFront(value) {
let node= new Node(value)
if(this.isEmpty()) {
this.head = node
this.tail = node
} else {
this.head.previous = node
node.next = this.head
this.head = node
}
this.size++
}
addToRear(value) {
let node= new Node(value)
if(this.isEmpty()) {
this.head = node
this.tail = node
} else {
this.tail.next = node
node.previous = this.tail
this.tail = node
}
this.size++
}
removeFromFront(){
if(this.isEmpty()) return
const removedNode = this.head
if (this.size === 1) {
this.head = null
this.tail = null
this.size - 
return removedNode.value
}
this.head = removedNode.next
this.head.previous = null
this.size--
return removedNode.value
}
removeFromRear(){
if(this.isEmpty()) return
const removedNode = this.tail
if (this.size === 1) {
this.head = null
this.tail = null
this.size - 
return removedNode.value
}
this.tail = removedNode.previous
this.tail.next = null
this.size--
return removedNode.value
}
peekFront() {
if(this.isEmpty()) return
return this.head.value
}
peekRear() {
if(this.isEmpty()) return
return this.tail.value
}
isEmpty() {
return this.size === 0
}
print() {
if(this.isEmpty()) return
let data = this.head
while(data) {
console.log(data.value)
data = data.next
}
}
}
let deque = new Deque()
deque.addToFront(5)
deque.addToRear(10)
deque.addToRear(15)
deque.addToRear(20)
deque.addToFront(2)
deque.print()
console.log(`Remove from front Value: ${deque.removeFromFront()}`)
console.log(`Remove from end Value: ${deque.removeFromRear()}`)
console.log(`Head Value: ${deque.peekFront()}`)
console.log(`Tail Value: ${deque.peekRear()}`)
deque.print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment