78 lines
1.3 KiB
TypeScript
78 lines
1.3 KiB
TypeScript
export interface DataNode<T> {
|
|
data: T;
|
|
next: DataNode<T> | null;
|
|
}
|
|
|
|
export interface QueueI<T> {
|
|
enqueue(data: T): void;
|
|
dequeue(): T | null;
|
|
peek(): T | null;
|
|
size(): number;
|
|
}
|
|
|
|
export class Queue<T> implements QueueI<T> {
|
|
private _size: number;
|
|
private head: DataNode<T> | null;
|
|
private tail: DataNode<T> | null;
|
|
constructor() {
|
|
this._size = 0;
|
|
this.head = this.tail = null;
|
|
}
|
|
|
|
enqueue(data: T) {
|
|
|
|
const node: DataNode<T> = {
|
|
data,
|
|
next: null
|
|
}
|
|
if (this.head === null) {
|
|
this.head = this.tail = node;
|
|
} else {
|
|
if (this.tail) {
|
|
this.tail.next = node;
|
|
this.tail = this.tail.next;
|
|
}
|
|
|
|
}
|
|
++this._size;
|
|
}
|
|
|
|
dequeue(): T | null {
|
|
|
|
let item: T | null = null;
|
|
|
|
if (this._size === 0) {
|
|
return null;
|
|
}
|
|
|
|
if (this.head) {
|
|
item = this.head.data;
|
|
this.head = this.head.next;
|
|
--this._size;
|
|
|
|
if (!this._size) {
|
|
this.tail = null;
|
|
}
|
|
}
|
|
return item;
|
|
}
|
|
|
|
peek(): T | null {
|
|
|
|
let item: T | null = null;
|
|
|
|
if (this._size === 0) {
|
|
return null;
|
|
}
|
|
|
|
if (this.head) {
|
|
item = this.head.data;
|
|
}
|
|
|
|
return item;
|
|
}
|
|
|
|
size(): number {
|
|
return this._size;
|
|
}
|
|
}
|