From 113e927a659a0c05f342d5766e999096d41727e9 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 3 Jul 2023 10:57:23 +0200 Subject: [PATCH] day(24): implement min heap Signed-off-by: Matej Focko --- src/data_structures/min_heap.rs | 28 ++++++++++++++++++++++++++++ src/data_structures/mod.rs | 2 ++ src/lib.rs | 3 +++ 3 files changed, 33 insertions(+) create mode 100644 src/data_structures/min_heap.rs create mode 100644 src/data_structures/mod.rs diff --git a/src/data_structures/min_heap.rs b/src/data_structures/min_heap.rs new file mode 100644 index 0000000..2996a82 --- /dev/null +++ b/src/data_structures/min_heap.rs @@ -0,0 +1,28 @@ +use std::cmp::{Ord, Reverse}; +use std::collections::BinaryHeap; + +pub struct MinHeap { + heap: BinaryHeap>, +} + +impl MinHeap { + pub fn new() -> MinHeap { + MinHeap { + heap: BinaryHeap::new(), + } + } + + pub fn push(&mut self, item: T) { + self.heap.push(Reverse(item)) + } + + pub fn pop(&mut self) -> Option { + self.heap.pop().map(|Reverse(x)| x) + } +} + +impl Default for MinHeap { + fn default() -> Self { + Self::new() + } +} diff --git a/src/data_structures/mod.rs b/src/data_structures/mod.rs new file mode 100644 index 0000000..07186ff --- /dev/null +++ b/src/data_structures/mod.rs @@ -0,0 +1,2 @@ +mod min_heap; +pub use min_heap::*; diff --git a/src/lib.rs b/src/lib.rs index 5245217..0286b60 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,3 +9,6 @@ pub use testing::*; mod vectors; pub use vectors::*; + +mod data_structures; +pub use data_structures::*;