forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.rs
78 lines (65 loc) · 1.57 KB
/
queue.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
use std::collections::LinkedList;
#[derive(Debug)]
pub struct Queue<T> {
elements: LinkedList<T>,
}
impl<T> Queue<T> {
pub fn new() -> Queue<T> {
Queue {
elements: LinkedList::new(),
}
}
pub fn enqueue(&mut self, value: T) {
self.elements.push_back(value)
}
pub fn dequeue(&mut self) -> Option<T> {
self.elements.pop_front()
}
pub fn peek_front(&self) -> Option<&T> {
self.elements.front()
}
pub fn len(&self) -> usize {
self.elements.len()
}
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}
}
impl<T> Default for Queue<T> {
fn default() -> Queue<T> {
Queue::new()
}
}
#[cfg(test)]
mod tests {
use super::Queue;
#[test]
fn test_enqueue() {
let mut queue: Queue<u8> = Queue::new();
queue.enqueue(64);
assert_eq!(queue.is_empty(), false);
}
#[test]
fn test_dequeue() {
let mut queue: Queue<u8> = Queue::new();
queue.enqueue(32);
queue.enqueue(64);
let retrieved_dequeue = queue.dequeue();
assert_eq!(retrieved_dequeue, Some(32));
}
#[test]
fn test_peek_front() {
let mut queue: Queue<u8> = Queue::new();
queue.enqueue(8);
queue.enqueue(16);
let retrieved_peek = queue.peek_front();
assert_eq!(retrieved_peek, Some(&8));
}
#[test]
fn test_size() {
let mut queue: Queue<u8> = Queue::new();
queue.enqueue(8);
queue.enqueue(16);
assert_eq!(2, queue.len());
}
}