#linked-list #algorithm #recursion #iterable #stack #heap #element

substack

Stackbound iterable linked list for heap-free recursive algorithms

3 stable releases

1.1.0 Nov 15, 2023
1.0.1 Oct 31, 2023

#805 in Algorithms

Download history 5/week @ 2024-02-15 22/week @ 2024-02-22 11/week @ 2024-02-29 4/week @ 2024-03-07 5/week @ 2024-03-14 9/week @ 2024-03-21 49/week @ 2024-03-28 8/week @ 2024-04-04

58 downloads per month
Used in orchidlang

MIT license

8KB
142 lines

A linked list on the stack to avoid heap allocations in recursive algorithms

use substack::Substack;

/// Walk a disjoint set and find the representative of an element, or return None if the
/// set contains a loop
fn find_value(alias_map: &[usize], idx: usize, prev: Substack<usize>) -> Option<usize> {
  match () {
    () if alias_map[idx] == idx => Some(idx),
    () if prev.iter().any(|i| *i == idx) => None,
    () => find_value(alias_map, alias_map[idx], prev.push(idx)),
  }
}

const map: &[usize] = &[2, 4, 1, 5, 1, 5];

assert_eq!(find_value(map, 0, Substack::Bottom), None);
assert_eq!(find_value(map, 3, Substack::Bottom), Some(5));

No runtime deps