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

}

相关推荐
GalaxyPokemon27 分钟前
归并排序:分治思想的高效排序
数据结构·算法·排序算法
ThreeYear_s29 分钟前
基于FPGA的PID算法学习———实现PI比例控制算法
学习·算法·fpga开发
Coding小公仔3 小时前
LeetCode 240 搜索二维矩阵 II
算法·leetcode·矩阵
C++chaofan3 小时前
74. 搜索二维矩阵
java·算法·leetcode·矩阵
青小莫4 小时前
数据结构-C语言-链表OJ
c语言·数据结构·链表
Studying 开龙wu4 小时前
机器学习监督学习实战五:六种算法对声呐回波信号进行分类
学习·算法·机器学习
Mi Manchi264 小时前
力扣热题100之二叉树的层序遍历
python·算法·leetcode
wu~9704 小时前
leetcode:42. 接雨水(秒变简单题)
算法·leetcode·职场和发展
zhurui_xiaozhuzaizai5 小时前
模型训练-关于token【低概率token, 高熵token】
人工智能·算法·自然语言处理