Created
November 30, 2021 05:23
-
-
Save vv13/624187bf3640a74632c17b94b31d8c95 to your computer and use it in GitHub Desktop.
[TS] Queue
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
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