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());

}

相关推荐
To_OC11 小时前
LC 994 腐烂的橘子:人人都说是 BFS 入门题,我却写了三遍才过
javascript·算法·leetcode
金銀銅鐵15 小时前
[Python] 扩展欧几里得算法
python·数学·算法
To_OC17 小时前
LC 200 岛屿数量:经典 DFS 入门题,我第一次写居然连方向都搞错了
javascript·算法·leetcode
星栈1 天前
我用 Rust + Dioxus 做了个全栈跨平台笔记应用:第一版先把列表和详情跑通
前端·rust·前端框架
doiito1 天前
【Agent Harness】Gliding Horse 工具结果压缩体系:如何用“指针”驯服上下文膨胀
ai·rust·架构设计·系统设计·ai agent
To_OC1 天前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
刘马想放假2 天前
Modbus 全栈技术解析:TCP、RTU、ASCII、RTU over TCP
数据结构·网络协议
星栈2 天前
Dioxus 接数据库最容易写歪的 3 个地方:sqlx + SQLite 怎么接才顺
前端·rust·前端框架
独孤留白2 天前
从C到Rust:移动语义、引用传递与生命周期——一次讲清楚
rust