Skip to content

Instantly share code, notes, and snippets.

@vv13
Created Nov 30, 2021
Embed
What would you like to do?
[TS] Queue
class Node<T> {
value: T
next?: Node<T>
constructor(value: T) {
this.value = value
}
}
class Queue<T> {
private _size = 0
private _head?: Node<T>
private _tail?: Node<T>
get size(): number {
return this._size
}
dequeue(): T | undefined {
if (!this._head) return
const current = this._head
this._head = this._head.next
this._size -= 1
return current.value
}
enqueue(item: T): void {
const newNode = new Node(item)
if (this._head && this._tail) {
this._tail.next = newNode
this._tail = newNode
} else {
this._head = newNode
this._tail = newNode
}
this._size += 1
}
clear(): void {
this._head = undefined
this._tail = undefined
this._size = 0
}
}
export default Queue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment