设计一个循环队列,具有固定大小,并能够支持队列的常规操作。
循环队列设计
循环队列是一种具有固定大小的队列,它支持常规的队列操作,如入队、出队、判断队列是否为空、判断队列是否已满等操作。循环队列的关键特性是当队列尾部指针指向队列尾部时,下一个元素将被插入到队列头部,实现了循环的效果。
数据结构
循环队列可以使用数组作为底层数据结构进行实现。需要记录队列的大小、队列的头部和尾部指针。
常规操作
- 入队:将元素插入到队列尾部,并更新队列尾部指针。
- 出队:从队列头部取出元素,并更新队列头部指针。
- 判断队列是否为空:队列头部和尾部指针相等时,队列为空。
- 判断队列是否已满:队列尾部的下一个位置是队列头部时,队列已满。
示例
以下是一个用 TypeScript 编写的循环队列示例:
class CircularQueue {
private queue: number[];
private capacity: number;
private head: number;
private tail: number;
constructor(capacity: number) {
this.capacity = capacity;
this.queue = new Array(capacity);
this.head = 0;
this.tail = 0;
}
enqueue(value: number): void {
if (this.isFull()) {
throw new Error('Queue is full');
}
this.queue[this.tail] = value;
this.tail = (this.tail + 1) % this.capacity;
}
dequeue(): number {
if (this.isEmpty()) {
throw new Error('Queue is empty');
}
const value = this.queue[this.head];
this.head = (this.head + 1) % this.capacity;
return value;
}
isEmpty(): boolean {
return this.head === this.tail;
}
isFull(): boolean {
return (this.tail + 1) % this.capacity === this.head;
}
}
此示例展示了使用 TypeScript 实现的循环队列,包括入队、出队、判断队列是否为空、判断队列是否已满等操作。