Created
April 20, 2023 06:57
-
-
Save armujahid/24aafeef72123a85c193bd62b38fe549 to your computer and use it in GitHub Desktop.
Useful Typescript classes
This file contains hidden or 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
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