rust实现循环队列

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.dataself.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.dataself.head.take();

self.head = (self.head + 1) % self.capacity;

value

}

fn is_empty(&self) -> bool {

if self.head == self.tail {

self.dataself.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());

}

相关推荐
倚楼听风语32 分钟前
Kotlin 协程与 suspend 原理详解
java·算法·kotlin
程序员清风34 分钟前
双指针与滑动窗口:高效处理连续区间
开发语言·算法
代钦塔拉39 分钟前
【C++/Qt 进阶】设计模式系列(2):工厂模式——从游戏角色到披萨店
c++·算法·设计模式
思茂信息44 分钟前
电磁仿真学涉及哪些算法?
人工智能·算法·数学建模·matlab·emc·电磁仿真·仿真辐射
糖果豆豆1 小时前
让 AI 自查三遍,它只会把错的说得更像对的——检查的人和被检查的,是同一个
算法·架构
总裁余(余登武)3 小时前
K-means算法改进(Python版)
python·算法·kmeans
灯澜忆梦3 小时前
【面向对象编程c++】| 指针与自定义数据类型
开发语言·c++·算法
xxwl5853 小时前
区域赛算法模版第八章---贪心(Greedy)
c++·笔记·学习·算法
alwaysrun3 小时前
Web之wasm-pack详解
前端·rust·web·wasm
CCblandy4 小时前
向量检索 ANN 参数实测:换一种数据分布,recall 掉了 51 个百分点
人工智能·python·算法·自然语言处理·性能优化