Skip to content

Instantly share code, notes, and snippets.

@mikeando
Created August 24, 2018 07:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeando/3ff947e20bb1a6bd415761d17f7e2860 to your computer and use it in GitHub Desktop.
Save mikeando/3ff947e20bb1a6bd415761d17f7e2860 to your computer and use it in GitHub Desktop.
pub struct CircularQueue<T> {
queue: Vec<Option<T>>,
head: usize,
tail: usize,
max_capacity: usize,
count: usize,
}
impl<T> CircularQueue<T> {
pub fn new(size: usize) -> CircularQueue<T> {
CircularQueue {
queue: Vec::with_capacity(size),
head: 0,
tail: 0,
max_capacity: size,
count: 0
}
}
fn is_full(&self) -> bool {
self.count == self.max_capacity
}
fn is_empty(&self) -> bool {
self.count == 0
}
pub fn enqueue(&mut self, item: T) -> Result<(), String>{
if self.is_full() {
return Err("Queue is full!".to_owned())
}
self.queue.insert(self.tail, Some(item));
self.tail = (self.tail + 1) % self.max_capacity;
self.count += 1;
Ok(())
}
pub fn dequeue(&mut self) -> Result<T, String> {
if self.is_empty() {
return Err("Queue is empty!".to_owned())
}
let item = std::mem::replace(&mut self.queue[self.head], None);
self.head = (self.head + 1) % self.max_capacity;
self.count -= 1;
Ok(item.unwrap())
}
}
fn main() {
let mut q = CircularQueue::<usize>::new(2);
q.enqueue(123).expect("Item 123 should be added");
println!("q.dequeue() == {}", q.dequeue().expect("Could not dequeue item"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment