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

}

相关推荐
我不会起名字3224 小时前
一天一道力扣Hot100(36):深度优先算法---组合总和
数据结构·c++·后端·python·算法·go
雨落在了我的手上4 小时前
Java数据结构(十五):哈希表
数据结构
虚无的纽扣4 小时前
【力扣刷题】第三天:有效三角形的个数、快乐数
算法·排序算法
tiger8654 小时前
大语言模型面试和题解,Context Engineering 怎么做?长 Prompt、动态上下文与 Memory 管理
人工智能·深度学习·算法·语言模型·自然语言处理·面试·nlp
不会就选b5 小时前
算法日常・每日刷题--<贪心>17
算法
6Hzlia7 小时前
【Classic 150 刷题计划】 LeetCode 205. 同构字符串 | C++ 双向绑定与哈希表映射
c++·算法·leetcode
有点。14 小时前
C++03阶段练习(练习题)
数据结构·算法·图论
周末也要写八哥15 小时前
经典算法实例:游戏中弱角色的数量(二)
算法
是Yu欸15 小时前
鸿蒙PC移植:2048 从网页小游戏到 AI 桌面应用
大数据·人工智能·算法·数据挖掘·openharmony·codex
鹿角片ljp16 小时前
KV Cache 解析
java·算法