Skip to content

Instantly share code, notes, and snippets.

@4skinSkywalker
Created April 23, 2019 12:42
Show Gist options
  • Save 4skinSkywalker/f662b8b6bda35487bd343be55c4be5c6 to your computer and use it in GitHub Desktop.
Save 4skinSkywalker/f662b8b6bda35487bd343be55c4be5c6 to your computer and use it in GitHub Desktop.
class Node {
constructor() {
this.value = null
this.prev = null
this.next = null
}
}
class Deque {
constructor() {
this.head = null
this.tail = null
this.size = 0
}
isEmpty() {
return this.head === null
}
size() {
return this.size
}
addFirst(value) {
let node = new Node()
node.value = value
node.next = this.head
node.prev = null
if (!this.head) {
this.head = node
this.tail = this.head
} else {
this.head.prev = node
this.head = node
}
}
addLast(value) {
let node = new Node()
node.value = value
node.next = null
node.prev = this.tail
if (!this.tail) {
this.tail = node
this.head = this.tail
} else {
this.tail.next = node
this.tail = node
}
}
removeLast() {
if (!this.tail) {
return null
}
if (!this.tail.prev) {
this.tail = null
this.head = null
} else {
this.tail = this.tail.prev
this.tail.next = null
}
}
removeFirst() {
if (!this.head) {
return null
}
if (!this.head.next) {
this.tail = null
this.head = null
} else {
this.head = this.head.next
this.head.prev = null
}
}
*[Symbol.iterator]() {
let node = this.head
while (node) {
yield node
node = node.next
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment