Skip to content

Instantly share code, notes, and snippets.

@intrnl
Last active December 21, 2020 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save intrnl/3b90e4680c9140bb3175a15da97d4c6c to your computer and use it in GitHub Desktop.
Save intrnl/3b90e4680c9140bb3175a15da97d4c6c to your computer and use it in GitHub Desktop.
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