Skip to content

Instantly share code, notes, and snippets.

@armujahid
Created April 20, 2023 06:57
Show Gist options
  • Save armujahid/24aafeef72123a85c193bd62b38fe549 to your computer and use it in GitHub Desktop.
Save armujahid/24aafeef72123a85c193bd62b38fe549 to your computer and use it in GitHub Desktop.
Useful Typescript classes
class Node<T> {
value: T;
next: Node<T> | null;
constructor(value: T) {
this.value = value;
this.next = null;
}
}
class Queue<T> {
head: Node<T> | null;
tail: Node<T> | null;
constructor() {
this.head = null;
this.tail = null;
}
enqueue(value: T): void {
const newNode = new Node(value);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else if (this.tail) {
this.tail.next = newNode;
this.tail = newNode;
}
}
dequeue(): T | null {
if (!this.head) return null;
const value = this.head.value;
this.head = this.head.next;
if (!this.head) {
this.tail = null;
}
return value;
}
isEmpty(): boolean {
return this.head === null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment