universo-platform-3d
59 строк · 1.1 Кб
1class QueueNode<T> {
2private _value: T
3public get value(): T {
4return this._value
5}
6public next: QueueNode<T> | null
7
8constructor(value: T) {
9this._value = value
10this.next = null
11}
12}
13
14class Queue<T> {
15private _first: QueueNode<T> | null = null
16public get first(): QueueNode<T> | null {
17return this._first
18}
19private _last: QueueNode<T> | null = null
20public get last(): QueueNode<T> | null {
21return this._last
22}
23private _size = 0
24public get size(): number {
25return this._size
26}
27
28public enqueue(value: T): number {
29const newNode = new QueueNode(value)
30if (!this._first) {
31this._first = newNode
32this._last = newNode
33} else {
34if (this._last) {
35this._last.next = newNode
36}
37this._last = newNode
38}
39
40return this._size++
41}
42
43public dequeue(): T | null {
44if (!this._first) {
45return null
46}
47
48const temp = this._first
49if (this._first === this._last) {
50this._last = null
51}
52
53this._first = this._first.next
54this._size--
55return temp.value
56}
57}
58
59export { Queue, QueueNode }
60