struct CircularQueue<T> {
data: Vec<Option<T>>,
head: usize,
tail: usize,
capacity: usize,
}
impl<T> CircularQueue<T> {
fn new(capacity: usize) -> Self {
let mut data = Vec::with_capacity(capacity);
for _ in 0..capacity {
data.push(None);
}
CircularQueue {
data,
head: 0,
tail: 0,
capacity,
}
}
fn enqueue(&mut self, value: T) -> bool {
if self.is_full() {
return false;
}
self.data[self.tail] = Some(value);
self.tail = (self.tail + 1) % self.capacity;
true
}
fn dequeue(&mut self) -> Option<T> {
if self.is_empty() {
return None;
}
let value = self.data[self.head].take();
self.head = (self.head + 1) % self.capacity;
value
}
fn is_empty(&self) -> bool {
if self.head == self.tail {
self.data[self.head].is_none()
} else {
false
}
}
fn is_full(&self) -> bool {
((self.tail + 1) % self.capacity) == self.head
}
}
fn main() {
let mut queue: CircularQueue<i32> = CircularQueue::new(3);
assert!(queue.enqueue(1));
assert!(queue.enqueue(2));
assert!(queue.enqueue(3));
assert!(!queue.enqueue(4)); // 队列满了,返回false
assert_eq!(queue.dequeue(), Some(1));
assert_eq!(queue.dequeue(), Some(2));
assert_eq!(queue.dequeue(), Some(3));
assert!(queue.is_empty());
}