Created
February 23, 2019 19:17
-
-
Save aalvarado/f25867ca7a501763c2025f5fddf54ed2 to your computer and use it in GitHub Desktop.
Naive circular queue in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fmt; | |
#[derive(Debug)] | |
struct CircularQueue<T> { | |
max: usize, | |
list: Vec<T>, | |
} | |
impl <T> CircularQueue<T> where T: std::string::ToString { | |
pub fn new(max: usize) -> CircularQueue<T> { | |
CircularQueue { | |
max: max, | |
list: Vec::new(), | |
} | |
} | |
pub fn enq(&mut self, number: T) { | |
self.list.push(number) | |
} | |
// Not really a `shift` here. The way remove works, is | |
// by removing the element and then shifting everything left. | |
pub fn deq(&mut self) -> T { | |
self.list.remove(0) | |
} | |
} | |
impl <T> fmt::Display for CircularQueue<T> where T: std::string::ToString { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
write!(f, "[{}]", | |
self.list.iter().fold(String::new(), |acc, num| acc + &num.to_string() + ", ") | |
) | |
} | |
} | |
fn main() { | |
let mut cq = CircularQueue::new(7); | |
cq.enq(1); | |
cq.enq(2); | |
println!("{}", cq); | |
cq.deq(); | |
println!("{}", cq); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment