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

}

相关推荐
Miraitowa_cheems1 天前
LeetCode算法日记 - Day 88: 环绕字符串中唯一的子字符串
java·数据结构·算法·leetcode·深度优先·动态规划
B站_计算机毕业设计之家1 天前
python电商商品评论数据分析可视化系统 爬虫 数据采集 Flask框架 NLP情感分析 LDA主题分析 Bayes评论分类(源码) ✅
大数据·hadoop·爬虫·python·算法·数据分析·1024程序员节
G_dou_1 天前
rust:第一个程序HelloWorld
rust
小白菜又菜1 天前
Leetcode 1518. Water Bottles
算法·leetcode·职场和发展
长存祈月心1 天前
Rust Option 与 Result深度解析
算法
杭州杭州杭州1 天前
机器学习(3)---线性算法,决策树,神经网络,支持向量机
算法·决策树·机器学习
G_dou_1 天前
Rust安装
开发语言·后端·rust
不语n1 天前
快速排序(Quick Sort)详解与图解
数据结构·算法·排序算法·快速排序·双指针排序
三萬Q1 天前
数据结构--并查集
数据结构