Last active
December 21, 2020 06:18
-
-
Save intrnl/3b90e4680c9140bb3175a15da97d4c6c to your computer and use it in GitHub Desktop.
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
export class Queue<V = any> { | |
head?: Node<V>; | |
tail?: Node<V>; | |
size!: number; | |
constructor () { | |
this.clear(); | |
} | |
enqueue (value: V): void { | |
let node: Node<V> = { value }; | |
if (this.tail) { | |
this.tail.next = node; | |
this.tail = node; | |
} else { | |
this.head = this.tail = node; | |
} | |
this.size++; | |
} | |
dequeue (): V | void { | |
let node = this.head; | |
if (!node) return; | |
this.head = this.head.next; | |
this.size--; | |
return node.value; | |
} | |
peek (): V | void { | |
if (this.head) return this.head.value; | |
} | |
clear (): void { | |
this.head = this.tail = undefined; | |
this.size = 0; | |
} | |
} | |
export interface Node<V> { | |
value: V, | |
next?: Node<V>, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment