-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathexercise_6_5_7.rs
More file actions
101 lines (82 loc) · 2.03 KB
/
Copy pathexercise_6_5_7.rs
File metadata and controls
101 lines (82 loc) · 2.03 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
use super::super::extra::{MaxPriorityQueue, MinPriorityQueue, VecMaxPriorityQueue, VecMinPriorityQueue};
use crate::chapter_10_elementary_data_structures::section_10_1_stacks_and_queues::extra::{Queue, Stack};
use crate::utilities::KeyValuePair;
pub struct FifoQueue<T> {
q: VecMinPriorityQueue<KeyValuePair<usize, T>>,
next_key: usize,
}
impl<T: Ord> Default for FifoQueue<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Ord> FifoQueue<T> {
#[must_use]
pub fn new() -> Self {
Self {
q: VecMinPriorityQueue::new(),
next_key: 0,
}
}
}
impl<T: Ord> Queue<T> for FifoQueue<T> {
fn empty(&self) -> bool {
self.q.empty()
}
fn enqueue(&mut self, x: T) {
self.q.insert(KeyValuePair::new(self.next_key, x));
self.next_key += 1;
}
fn dequeue(&mut self) -> T {
self.q.extract_min().value
}
fn length(&self) -> usize {
self.q.length()
}
}
pub struct LifoStack<T> {
q: VecMaxPriorityQueue<KeyValuePair<usize, T>>,
next_key: usize,
}
impl<T: Ord> Default for LifoStack<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Ord> LifoStack<T> {
#[must_use]
pub fn new() -> Self {
Self {
q: VecMaxPriorityQueue::new(),
next_key: 0,
}
}
}
impl<T: Ord> Stack<T> for LifoStack<T> {
fn empty(&self) -> bool {
self.q.empty()
}
fn push(&mut self, x: T) {
self.q.insert(KeyValuePair::new(self.next_key, x));
self.next_key += 1;
}
fn pop(&mut self) -> T {
self.q.extract_max().value
}
fn length(&self) -> usize {
self.q.length()
}
}
#[cfg(test)]
mod tests {
use super::{FifoQueue, LifoStack};
use crate::chapter_10_elementary_data_structures::section_10_1_stacks_and_queues::tests;
#[test]
fn test_fifo_queue() {
tests::run_queue_test_cases(FifoQueue::new);
}
#[test]
fn test_lifo_stack() {
tests::run_stack_test_cases(LifoStack::new);
}
}