rust_dsa

Struct MinStack

Source
pub struct MinStack<T> { /* private fields */ }
Expand description

A LIFO stack that supports O(1) push, pop and find-minimum.

Internally, each element on the stack contains a value and the index of the minimum value below it (or itself if it is smaller than everything below it). Each time we push, we compare the new value to the smallest value already on the stack. If it is smaller, we push the new value with its own index. Otherwise, we push the new value with the index of the smaller value that was already on the stack.

To find the minimum value, we just use the index of the last element on the stack.

§Example

use rust_dsa::MinStack;

// First, we create a new stack.
let mut stack = MinStack::new();

// We can push elements.
stack.push(2);
stack.push(3);
stack.push(6);
stack.push(1);

// We can get the minimum element.
assert_eq!(stack.get_min(), Some(&1));

// We can peek and pop as usual.
assert_eq!(stack.peek(), Some(&1));
assert_eq!(stack.pop(), Some(1));

// The min element reflects the stack's new state.
assert_eq!(stack.get_min(), Some(&2));

// We can iterate over the stack.
for x in stack {
    // Prints 6, 3 and 2.
    println!("{x}");
}

// We can also create stacks from arrays.
let a = MinStack::from(['s', 't', 'a', 'c', 'k']);

// And iterators.
let b: MinStack<_> = "stack".chars().collect();

assert!(a == b);

Implementations§

Source§

impl<T> MinStack<T>

Source

pub fn new() -> MinStack<T>

Creates an empty stack.

Source

pub fn with_capacity(capacity: usize) -> MinStack<T>

Creates an empty stack with the specified capacity.

Source

pub fn push(&mut self, value: T)
where T: Ord,

Pushes an element onto the top of the stack.

§Example
use rust_dsa::MinStack;

let mut stack = MinStack::new();
stack.push(5);

assert_eq!(stack.pop(), Some(5));
assert_eq!(stack.pop(), None);
Source

pub fn pop(&mut self) -> Option<T>

Removes the last element on the stack and returns it or None if the stack is empty.

§Example
use rust_dsa::MinStack;

let mut stack = MinStack::from([5]);

assert_eq!(stack.pop(), Some(5));
assert_eq!(stack.pop(), None);
Source

pub fn peek(&self) -> Option<&T>

Returns a reference the last element on the stack or None if the stack is empty.

§Example
use rust_dsa::MinStack;

let mut stack = MinStack::from(['a']);

assert_eq!(stack.peek(), Some(&'a'));

stack.pop();

assert_eq!(stack.peek(), None);
Source

pub fn get_min(&mut self) -> Option<&T>

Returns the smallest element on the stack or None if the stack is empty.

§Example
use rust_dsa::MinStack;

let mut stack = MinStack::from([5, 3, 4, 8, 2, 6, 1]);

assert_eq!(stack.get_min(), Some(&1));

stack.pop();

assert_eq!(stack.get_min(), Some(&2));

stack.clear();

assert_eq!(stack.get_min(), None);
Source

pub fn len(&self) -> usize

Returns the number of elements on the stack.

§Example
use rust_dsa::MinStack;

let mut stack = MinStack::from([5, 3, 4, 8, 2, 6, 1]);

assert_eq!(stack.len(), 7);

stack.clear();

assert_eq!(stack.len(), 0);
Source

pub fn is_empty(&self) -> bool

Returns true if the stack is empty.

§Example
use rust_dsa::MinStack;

let mut stack = MinStack::from([5, 3, 4, 8, 2, 6, 1]);

assert!(!stack.is_empty());

stack.clear();

assert!(stack.is_empty());
Source

pub fn clear(&mut self)

Clears the stack.

§Example
use rust_dsa::MinStack;

let mut stack = MinStack::from([5, 3, 4, 8, 2, 6, 1]);

assert!(!stack.is_empty());

stack.clear();

assert!(stack.is_empty());

Trait Implementations§

Source§

impl<T: Clone> Clone for MinStack<T>

Source§

fn clone(&self) -> MinStack<T>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> Debug for MinStack<T>
where T: Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> Default for MinStack<T>

Source§

fn default() -> MinStack<T>

Returns the “default value” for a type. Read more
Source§

impl<T, const N: usize> From<[T; N]> for MinStack<T>
where T: Ord,

Source§

fn from(array: [T; N]) -> MinStack<T>

Converts to this type from the input type.
Source§

impl<T> FromIterator<T> for MinStack<T>
where T: Ord,

Source§

fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> MinStack<T>

Creates a value from an iterator. Read more
Source§

impl<'a, T> IntoIterator for &'a MinStack<T>

Source§

type IntoIter = Iter<'a, T>

Which kind of iterator are we turning this into?
Source§

type Item = &'a T

The type of the elements being iterated over.
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<T> IntoIterator for MinStack<T>

Source§

type IntoIter = IntoIter<T>

Which kind of iterator are we turning this into?
Source§

type Item = T

The type of the elements being iterated over.
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<T> PartialEq for MinStack<T>
where T: PartialEq,

Source§

fn eq(&self, other: &MinStack<T>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: Eq> Eq for MinStack<T>

Auto Trait Implementations§

§

impl<T> Freeze for MinStack<T>

§

impl<T> RefUnwindSafe for MinStack<T>
where T: RefUnwindSafe,

§

impl<T> Send for MinStack<T>
where T: Send,

§

impl<T> Sync for MinStack<T>
where T: Sync,

§

impl<T> Unpin for MinStack<T>
where T: Unpin,

§

impl<T> UnwindSafe for MinStack<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.