1
0
Files
test-kata-machine/src/day1/Queue.ts
2025-12-17 07:57:42 +00:00

51 lines
968 B
TypeScript

type Node<T> = {
value: T;
next?: Node<T>;
};
export default class Queue<T> {
public length: number;
private head?: Node<T>;
private tail?: Node<T>;
constructor() {
this.head = undefined;
this.tail = undefined;
this.length = 0;
}
enqueue(item: T): void {
const node = { value: item } as Node<T>;
this.length++;
if (!this.tail) {
this.head = node;
this.tail = node;
return;
}
this.tail.next = node;
this.tail = node;
}
deque(): T | undefined {
if (!this.head) {
return undefined;
}
this.length--;
const head = this.head;
this.head = this.head.next;
head.next = undefined;
if (this.length === 0) {
this.tail = undefined;
}
return head.value;
}
peek(): T | undefined {
return this.head?.value;
}
}