Elysia Tools

Browse tools, examples, visual explainers, and topic guides from one clear workspace.

Top Categories

Hubs

Language
ZHESPTRUFRDEEN

Elysia Tools

Navigation

Rust

Rust data structures: sequence, lookup and links

Choose between sequence operations, keyed lookup and node-based structures.

Samples

Entries inside this sample collection

CoderustSimple

Array/Vector Operations

Vector manipulation including CRUD operations, sorting, searching, and transformations

Difficulty

4/10

Estimated time

20 min

Tags

rust, web, data structures

Prerequisites

Basic Rust

rust
// Web Rust Array/Vector Operations Examples
// Using Rust Vec<T> for dynamic arrays

// 1. Vector Creation and Basic Operations

/// Create a new vector
fn create_vector() -> Vec<i32> {
    vec![1, 2, 3, 4, 5]
}

/// Create vector with capacity
fn create_vector_with_capacity() -> Vec<i32> {
    Vec::with_capacity(10)
}

/// Add elements to vector
fn add_elements() -> Vec<i32> {
    let mut vec = Vec::new();
    vec.push(1);
    vec.push(2);
    vec.push(3);
    vec
}

// 2. CRUD Operations

/// Read element at index
fn read_element(vec: &Vec<i32>, index: usize) -> Option<&i32> {
    vec.get(index)
}

/// Update element at index
fn update_element(vec: &mut Vec<i32>, index: usize, value: i32) -> Result<(), String> {
    if index < vec.len() {
        vec[index] = value;
        Ok(())
    } else {
        Err(format!("Index {} out of bounds", index))
    }
}

/// Delete element at index
fn delete_element(vec: &mut Vec<i32>, index: usize) -> Result<i32, String> {
    if index < vec.len() {
        Ok(vec.remove(index))
    } else {
        Err(format!("Index {} out of bounds", index))
    }
}

// 3. Vector Operations

/// Find element
fn find_element(vec: &Vec<i32>, target: i32) -> Option<usize> {
    vec.iter().position(|&x| x == target)
}

/// Contains element
fn contains_element(vec: &Vec<i32>, target: i32) -> bool {
    vec.contains(&target)
}

/// Count occurrences
fn count_occurrences(vec: &Vec<i32>, target: i32) -> usize {
    vec.iter().filter(|&&x| x == target).count()
}

/// Reverse vector
fn reverse_vector(vec: &mut Vec<i32>) {
    vec.reverse();
}

/// Clear vector
fn clear_vector(vec: &mut Vec<i32>) {
    vec.clear();
}

// 4. Sorting

/// Sort in ascending order
fn sort_ascending(vec: &mut Vec<i32>) {
    vec.sort();
}

/// Sort in descending order
fn sort_descending(vec: &mut Vec<i32>) {
    vec.sort_by(|a, b| b.cmp(a));
}

/// Sort with custom comparator
fn sort_custom(vec: &mut Vec<i32>) {
    vec.sort_by(|a, b| {
        // Sort by absolute value
        a.abs().cmp(&b.abs())
    });
}

// 5. Searching

/// Binary search on sorted vector
fn binary_search(vec: &[i32], target: i32) -> Option<usize> {
    vec.binary_search(&target).ok()
}

/// Find min and max
fn find_min_max(vec: &[i32]) -> Option<(i32, i32)> {
    if vec.is_empty() {
        return None;
    }
    let min = vec.iter().min()?;
    let max = vec.iter().max()?;
    Some((*min, *max))
}

// 6. Transformations

/// Map: square each element
fn map_square(vec: &[i32]) -> Vec<i32> {
    vec.iter().map(|&x| x * x).collect()
}

/// Filter: keep even numbers
fn filter_even(vec: &[i32]) -> Vec<i32> {
    vec.iter().filter(|&&x| x % 2 == 0).copied().collect()
}

/// Fold: sum all elements
fn fold_sum(vec: &[i32]) -> i32 {
    vec.iter().sum()
}

/// Combine operations: sum of squares
fn sum_of_squares(vec: &[i32]) -> i32 {
    vec.iter().map(|&x| x * x).sum()
}

// 7. Vector Manipulation

/// Concatenate two vectors
fn concatenate(vec1: &[i32], vec2: &[i32]) -> Vec<i32> {
    [vec1, vec2].concat()
}

/// Split vector at index
fn split_at(vec: &[i32], index: usize) -> (&[i32], &[i32]) {
    vec.split_at(index)
}

/// Chunk vector into smaller vectors
fn chunk_vector(vec: &[i32], chunk_size: usize) -> Vec<&[i32]> {
    vec.chunks(chunk_size).collect()
}

/// Window sliding
fn sliding_window(vec: &[i32], window_size: usize) -> Vec<&[i32]> {
    vec.windows(window_size).collect()
}

// 8. Deduplication

/// Remove consecutive duplicates
fn dedup_consecutive(vec: &mut Vec<i32>) {
    vec.dedup();
}

/// Remove all duplicates
fn dedup_all(vec: &[i32]) -> Vec<i32> {
    let mut seen = std::collections::HashSet::new();
    vec.iter().filter(|x| seen.insert(*x)).copied().collect()
}

// 9. Vector Operations with Predicates

/// Check if all elements satisfy predicate
fn all_positive(vec: &[i32]) -> bool {
    vec.iter().all(|&x| x > 0)
}

/// Check if any element satisfies predicate
fn any_negative(vec: &[i32]) -> bool {
    vec.iter().any(|&x| x < 0)
}

// 10. Advanced Operations

/// Rotate vector left
fn rotate_left(vec: &mut Vec<i32>, k: usize) {
    vec.rotate_left(k);
}

/// Rotate vector right
fn rotate_right(vec: &mut Vec<i32>, k: usize) {
    vec.rotate_right(k);
}

/// Swap two elements
fn swap_elements(vec: &mut Vec<i32>, i: usize, j: usize) -> Result<(), String> {
    if i >= vec.len() || j >= vec.len() {
        return Err("Index out of bounds".to_string());
    }
    vec.swap(i, j);
    Ok(())
}

/// Resize vector
fn resize_vector(vec: &mut Vec<i32>, new_len: usize, value: i32) {
    vec.resize(new_len, value);
}

// Usage Examples
fn main() {
    println!("=== Web Rust Array/Vector Operations Examples ===\n");

    // 1. Create vector
    println!("--- 1. Create Vector ---");
    let mut vec = create_vector();
    println!("Vector: {:?}", vec);

    // 2. CRUD operations
    println!("\n--- 2. CRUD Operations ---");
    vec.push(6);
    println!("After push: {:?}", vec);
    println!("Element at index 2: {:?}", read_element(&vec, 2));
    update_element(&mut vec, 2, 10).unwrap();
    println!("After update: {:?}", vec);
    delete_element(&mut vec, 3).unwrap();
    println!("After delete: {:?}", vec);

    // 3. Searching
    println!("\n--- 3. Searching ---");
    let vec = vec
![1, 5, 3, 7, 2, 9, 4];
    println!("Vector: {:?}", vec);
    println!("Find 3: {:?}", find_element(&vec, 3));
    println!("Contains 5: {}", contains_element(&vec, 5));
    println!("Min/Max: {:?}", find_min_max(&vec));

    // 4. Sorting
    println!("\n--- 4. Sorting ---");
    let mut vec = vec
![3, 1, 4, 1, 5, 9, 2, 6];
    println!("Original: {:?}", vec);
    sort_ascending(&mut vec);
    println!("Ascending: {:?}", vec);
    sort_descending(&mut vec);
    println!("Descending: {:?}", vec);

    // 5. Transformations
    println!("\n--- 5. Transformations ---");
    let vec = vec
![1, 2, 3, 4, 5];
    println!("Original: {:?}", vec);
    println!("Squared: {:?}", map_square(&vec));
    println!("Even: {:?}", filter_even(&vec));
    println!("Sum: {}", fold_sum(&vec));
    println!("Sum of squares: {}", sum_of_squares(&vec));

    // 6. Manipulation
    println!("\n--- 6. Manipulation ---");
    let vec1 = vec
![1, 2, 3];
    let vec2 = vec
![4, 5, 6];
    println!("Concat: {:?}", concatenate(&vec1, &vec2));
    println!("Chunks: {:?}", chunk_vector(&[1, 2, 3, 4, 5, 6, 7], 3));

    // 7. Deduplication
    println!("\n--- 7. Deduplication ---");
    let mut vec = vec
![1, 1, 2, 2, 3, 3, 3];
    println!("Original: {:?}", vec);
    dedup_consecutive(&mut vec);
    println!("After dedup: {:?}", vec);

    // 8. Predicates
    println!("\n--- 8. Predicates ---");
    let vec = vec
![1, 2, 3, 4, 5];
    println!("All positive: {}", all_positive(&vec));
    println!("Any negative: {}", any_negative(&vec));

    println!("\n=== All Array/Vector Operations Completed ===");
}
CoderustIntermediate

Hash Map Operations

HashMap usage for key-value storage and retrieval with various operations

Difficulty

5/10

Estimated time

25 min

Tags

rust, web, data structures, hashmap

Prerequisites

Basic Rust, std::collections

rust
// Web Rust HashMap Operations Examples
// Using std::collections::HashMap for key-value storage

use std::collections::HashMap;

// 1. Basic HashMap Operations

/// Create a new HashMap
fn create_hashmap() -> HashMap<String, i32> {
    HashMap::new()
}

/// Create HashMap with initial values
fn create_hashmap_with_values() -> HashMap<String, i32> {
    let mut map = HashMap::new();
    map.insert("apple".to_string(), 5);
    map.insert("banana".to_string(), 3);
    map.insert("orange".to_string(), 7);
    map
}

/// Insert key-value pair
fn insert_pair(map: &mut HashMap<String, i32>, key: String, value: i32) {
    map.insert(key, value);
}

/// Get value by key
fn get_value(map: &HashMap<String, i32>, key: &str) -> Option<i32> {
    map.get(key).copied()
}

/// Remove key-value pair
fn remove_pair(map: &mut HashMap<String, i32>, key: &str) -> Option<i32> {
    map.remove(key)
}

// 2. HashMap Operations

/// Check if key exists
fn contains_key(map: &HashMap<String, i32>, key: &str) -> bool {
    map.contains_key(key)
}

/// Get map size
fn get_size(map: &HashMap<String, i32>) -> usize {
    map.len()
}

/// Check if map is empty
fn is_empty(map: &HashMap<String, i32>) -> bool {
    map.is_empty()
}

/// Clear all entries
fn clear_map(map: &mut HashMap<String, i32>) {
    map.clear();
}

// 3. Entry API

/// Insert or update using entry API
fn insert_or_update(map: &mut HashMap<String, i32>, key: String, value: i32) {
    map.entry(key).and_modify(|v| *v = value).or_insert(value);
}

/// Insert only if key doesn't exist
fn insert_if_absent(map: &mut HashMap<String, i32>, key: String, value: i32) -> bool {
    map.entry(key).or_insert(value);
    true
}

/// Update value if key exists
fn update_if_exists(map: &mut HashMap<String, i32>, key: &str, f: impl FnOnce(&mut i32)) -> bool {
    if let Some(v) = map.get_mut(key) {
        f(v);
        true
    } else {
        false
    }
}

// 4. Iteration

/// Iterate over keys
fn iterate_keys(map: &HashMap<String, i32>) -> Vec<&String> {
    map.keys().collect()
}

/// Iterate over values
fn iterate_values(map: &HashMap<String, i32>) -> Vec<&i32> {
    map.values().collect()
}

/// Iterate over key-value pairs
fn iterate_pairs(map: &HashMap<String, i32>) -> Vec<(&String, &i32)> {
    map.iter().collect()
}

// 5. HashMap Transformations

/// Filter entries
fn filter_map(map: &HashMap<String, i32>, predicate: impl Fn(&i32) -> bool) -> HashMap<String, i32> {
    map.iter()
        .filter(|(_, v)| predicate(v))
        .map(|(k, v)| (k.clone(), *v))
        .collect()
}

/// Map values
fn map_values<F>(map: &HashMap<String, i32>, f: F) -> HashMap<String, i32>
where
    F: Fn(i32) -> i32,
{
    map.iter()
        .map(|(k, v)| (k.clone(), f(*v)))
        .collect()
}

// 6. Advanced Operations

/// Merge two HashMaps
fn merge_maps(map1: &HashMap<String, i32>, map2: &HashMap<String, i32>) -> HashMap<String, i32> {
    let mut result = map1.clone();
    for (key, value) in map2 {
        result.entry(key.clone()).or_insert(*value);
    }
    result
}

/// Clone keys
fn get_keys(map: &HashMap<String, i32>) -> Vec<String> {
    map.keys().cloned().collect()
}

/// Clone values
fn get_values_clone(map: &HashMap<String, i32>) -> Vec<i32> {
    map.values().cloned().collect()
}

/// Reserve capacity
fn reserve_capacity(map: &mut HashMap<String, i32>, additional: usize) {
    map.reserve(additional);
}

/// Shrink to fit
fn shrink_to_fit(map: &mut HashMap<String, i32>) {
    map.shrink_to_fit();
}

// 7. Counter using HashMap

/// Count occurrences
fn count_occurrences<T>(items: Vec<T>) -> HashMap<T, usize>
where
    T: std::hash::Hash + Eq + Clone,
{
    let mut counter = HashMap::new();
    for item in items {
        *counter.entry(item).or_insert(0) += 1;
    }
    counter
}

/// Count words
fn count_words(text: &str) -> HashMap<String, usize> {
    let mut counter = HashMap::new();
    for word in text.split_whitespace() {
        let word = word.to_lowercase();
        *counter.entry(word).or_insert(0) += 1;
    }
    counter
}

// 8. Grouping

/// Group values by key
fn group_by_key(items: Vec<(String, i32)>) -> HashMap<String, Vec<i32>> {
    let mut grouped: HashMap<String, Vec<i32>> = HashMap::new();
    for (key, value) in items {
        grouped.entry(key).or_insert_with(Vec::new).push(value);
    }
    grouped
}

// 9. HashMap with Custom Types

#[derive(Debug, PartialEq, Eq, Hash)]
struct Person {
    name: String,
    age: u32,
}

impl Person {
    fn new(name: &str, age: u32) -> Self {
        Person {
            name: name.to_string(),
            age,
        }
    }
}

/// HashMap with custom key
fn custom_key_example() -> HashMap<Person, String> {
    let mut map = HashMap::new();
    map.insert(Person::new("Alice", 30), "Engineer".to_string());
    map.insert(Person::new("Bob", 25), "Designer".to_string());
    map
}

// 10. Default Values

/// Get value or default
fn get_or_default(map: &HashMap<String, i32>, key: &str, default: i32) -> i32 {
    *map.get(key).unwrap_or(&default)
}

/// Get value or compute default
fn get_or_compute<F>(map: &HashMap<String, i32>, key: &str, f: F) -> i32
where
    F: FnOnce() -> i32,
{
    *map.get(key).unwrap_or(&f())
}

// Usage Examples
fn main() {
    println!("=== Web Rust HashMap Operations Examples ===\n");

    // 1. Create and insert
    println!("--- 1. Create and Insert ---");
    let mut map = create_hashmap();
    insert_pair(&mut map, "apple".to_string(), 5);
    insert_pair(&mut map, "banana".to_string(), 3);
    println!("Map: {:?}", map);

    // 2. Get and remove
    println!("\n--- 2. Get and Remove ---");
    println!("Get 'apple': {:?}", get_value(&map, "apple"));
    println!("Remove 'banana': {:?}", remove_pair(&mut map, "banana"));
    println!("After remove: {:?}", map);

    // 3. Entry API
    println!("\n--- 3. Entry API ---");
    let mut map = create_hashmap_with_values();
    insert_or_update(&mut map, "apple".to_string(), 10);
    println!("After update: {:?}", map);

    // 4. Iteration
    println!("\n--- 4. Iteration ---");
    let map = create_hashmap_with_values();
    println!("Keys: {:?}", iterate_keys(&map));
    println!("Values: {:?}", iterate_values(&map));

    // 5. Filter and map
    println!("\n--- 5. Filter and Map ---");
    let filtered = filter_map(&map, |&v| v > 4);
    println!("Filtered (>4): {:?}", filtered);
    let doubled = map_values(&map, |v| v * 2);
    println!("Doubled: {:?}", doubled);

    // 6. Counter
    println!("\n--- 6. Counter ---");
    let items = vec
!["apple", "banana", "apple", "orange", "banana", "apple"];
    let counter = count_occurrences(items);
    println!("Counts: {:?}", counter);

    // 7. Word count
    println!("\n--- 7. Word Count ---");
    let text = "hello world hello rust world";
    let word_counts = count_words(text);
    println!("Word counts: {:?}", word_counts);

    // 8. Grouping
    println!("\n--- 8. Grouping ---");
    let items = vec
![
        ("fruit".to_string(), 1),
        ("fruit".to_string(), 2),
        ("veg".to_string(), 3),
    ];
    let grouped = group_by_key(items);
    println!("Grouped: {:?}", grouped);

    // 9. Custom key
    println!("\n--- 9. Custom Key ---");
    let custom_map = custom_key_example();
    println!("Custom map: {:?}", custom_map);

    println!("\n=== All HashMap Operations Completed ===");
}
CoderustIntermediate

Linked List

Implement and use singly and doubly linked lists in Rust

Difficulty

7/10

Estimated time

30 min

Tags

rust, web, data structures, linked list

Prerequisites

Intermediate Rust, ownership, Box, references

rust
// Web Rust Linked List Examples
// Implementing singly and doubly linked lists

// 1. Singly Linked List

/// Node for singly linked list
#[derive(Debug)]
struct ListNode {
    value: i32,
    next: Option<Box<ListNode>>,
}

impl ListNode {
    fn new(value: i32) -> Self {
        ListNode { value, next: None }
    }
}

/// Singly linked list
#[derive(Debug)]
struct LinkedList {
    head: Option<Box<ListNode>>,
    size: usize,
}

impl LinkedList {
    fn new() -> Self {
        LinkedList { head: None, size: 0 }
    }

    /// Push to front
    fn push_front(&mut self, value: i32) {
        let mut new_node = Box::new(ListNode::new(value));
        new_node.next = self.head.take();
        self.head = Some(new_node);
        self.size += 1;
    }

    /// Push to back
    fn push_back(&mut self, value: i32) {
        let new_node = Box::new(ListNode::new(value));

        match self.head {
            None => {
                self.head = Some(new_node);
            }
            Some(ref mut head) => {
                let mut current = head;
                while current.next.is_some() {
                    current = current.next.as_mut().unwrap();
                }
                current.next = Some(new_node);
            }
        }
        self.size += 1;
    }

    /// Pop from front
    fn pop_front(&mut self) -> Option<i32> {
        self.head.take().map(|node| {
            self.head = node.next;
            self.size -= 1;
            node.value
        })
    }

    /// Get size
    fn len(&self) -> usize {
        self.size
    }

    /// Check if empty
    fn is_empty(&self) -> bool {
        self.head.is_none()
    }

    /// Convert to vector
    fn to_vec(&self) -> Vec<i32> {
        let mut result = Vec::new();
        let mut current = &self.head;
        while let Some(node) = current {
            result.push(node.value);
            current = &node.next;
        }
        result
    }

    /// Find value
    fn find(&self, target: i32) -> bool {
        let mut current = &self.head;
        while let Some(node) = current {
            if node.value == target {
                return true;
            }
            current = &node.next;
        }
        false
    }

    /// Reverse the list
    fn reverse(&mut self) {
        let mut prev = None;
        let mut current = self.head.take();

        while let Some(mut node) = current {
            let next = node.next.take();
            node.next = prev;
            prev = Some(node);
            current = next;
        }

        self.head = prev;
    }
}

// 2. Doubly Linked List

/// Node for doubly linked list
#[derive(Debug)]
struct DoublyListNode {
    value: i32,
    prev: Option<*mut DoublyListNode>,
    next: Option<Box<DoublyListNode>>,
}

/// Doubly linked list
#[derive(Debug)]
struct DoublyLinkedList {
    head: Option<Box<DoublyListNode>>,
    tail: Option<*mut DoublyListNode>,
    size: usize,
}

impl DoublyLinkedList {
    fn new() -> Self {
        DoublyLinkedList {
            head: None,
            tail: None,
            size: 0,
        }
    }

    /// Push to front
    fn push_front(&mut self, value: i32) {
        let mut new_node = Box::new(DoublyListNode {
            value,
            prev: None,
            next: self.head.take(),
        });

        let new_node_ptr: *mut DoublyListNode = &mut *new_node;
        if let Some(next) = new_node.next.as_mut() {
            next.prev = Some(new_node_ptr);
        } else {
            self.tail = Some(new_node_ptr);
        }

        self.head = Some(new_node);
        self.size += 1;
    }

    /// Push to back
    fn push_back(&mut self, value: i32) {
        let mut new_node = Box::new(DoublyListNode {
            value,
            prev: self.tail,
            next: None,
        });

        match self.tail {
            Some(tail) => {
                unsafe {
                    (*tail).next = Some(new_node);
                }
                self.tail = unsafe {
                    (*tail).next.as_mut().map(|node| &mut **node as *mut _)
                };
            }
            None => {
                self.head = Some(new_node);
                self.tail = self.head.as_mut().map(|node| &mut **node as *mut _);
            }
        }
        self.size += 1;
    }

    /// Get size
    fn len(&self) -> usize {
        self.size
    }

    /// Check if empty
    fn is_empty(&self) -> bool {
        self.head.is_none()
    }
}

// 3. Circular Linked List

/// Circular linked list (simplified)
#[derive(Debug)]
struct CircularLinkedList {
    head: Option<Box<ListNode>>,
    size: usize,
}

impl CircularLinkedList {
    fn new() -> Self {
        CircularLinkedList { head: None, size: 0 }
    }

    /// Insert at end (simplified append implementation)
    fn insert(&mut self, value: i32) {
        let new_node = Box::new(ListNode::new(value));

        match self.head.as_mut() {
            None => self.head = Some(new_node),
            Some(head) => {
                let mut current = head;
                while let Some(ref mut next) = current.next {
                    current = next;
                }
                current.next = Some(new_node);
            }
        }
        self.size += 1;
    }

    /// Get size
    fn len(&self) -> usize {
        self.size
    }
}

// 4. Linked List Algorithms

/// Merge two sorted linked lists
fn merge_sorted_lists(list1: LinkedList, list2: LinkedList) -> LinkedList {
    let mut result = LinkedList::new();
    let mut vec1 = list1.to_vec();
    let mut vec2 = list2.to_vec();

    vec1.sort();
    vec2.sort();

    // Merge
    let mut i = 0;
    let mut j = 0;
    while i < vec1.len() && j < vec2.len() {
        if vec1[i] <= vec2[j] {
            result.push_back(vec1[i]);
            i += 1;
        } else {
            result.push_back(vec2[j]);
            j += 1;
        }
    }

    while i < vec1.len() {
        result.push_back(vec1[i]);
        i += 1;
    }

    while j < vec2.len() {
        result.push_back(vec2[j]);
        j += 1;
    }

    result
}

/// Detect cycle in linked list
fn has_cycle(list: &LinkedList) -> bool {
    // Simplified version - real implementation would use Floyd's algorithm
    list.to_vec().len() != list.len()
}

/// Find middle element
fn find_middle(list: &LinkedList) -> Option<i32> {
    let vec = list.to_vec();
    if vec.is_empty() {
        return None;
    }
    Some(vec[vec.len() / 2])
}

/// Remove nth node from end
fn remove_nth_from_end(list: &mut LinkedList, n: usize) -> Option<i32> {
    let len = list.len();
    if n == 0 || n > len {
        return None;
    }

    let target_index = len - n;
    // Simplified - real implementation would modify actual list
    let vec = list.to_vec();
    Some(vec[target_index])
}

// 5. Stack using Linked List

/// Stack implemented with linked list
#[derive(Debug)]
struct Stack {
    list: LinkedList,
}

impl Stack {
    fn new() -> Self {
        Stack { list: LinkedList::new() }
    }

    fn push(&mut self, value: i32) {
        self.list.push_front(value);
    }

    fn pop(&mut self) -> Option<i32> {
        self.list.pop_front()
    }

    fn peek(&self) -> Option<i32> {
        self.list.head.as_ref().map(|node| node.value)
    }

    fn is_empty(&self) -> bool {
        self.list.is_empty()
    }
}

// 6. Queue using Linked List

/// Queue implemented with linked list
#[derive(Debug)]
struct Queue {
    list: LinkedList,
}

impl Queue {
    fn new() -> Self {
        Queue { list: LinkedList::new() }
    }

    fn enqueue(&mut self, value: i32) {
        self.list.push_back(value);
    }

    fn dequeue(&mut self) -> Option<i32> {
        self.list.pop_front()
    }

    fn front(&self) -> Option<i32> {
        self.list.head.as_ref().map(|node| node.value)
    }

    fn is_empty(&self) -> bool {
        self.list.is_empty()
    }
}

// Usage Examples
fn main() {
    println!("=== Web Rust Linked List Examples ===\n");

    // 1. Singly linked list
    println!("--- 1. Singly Linked List ---");
    let mut list = LinkedList::new();
    list.push_back(1);
    list.push_back(2);
    list.push_back(3);
    println!("List: {:?}", list.to_vec());
    println!("Size: {}", list.len());
    println!("Contains 2: {}", list.find(2));

    // 2. Reverse
    println!("\n--- 2. Reverse List ---");
    list.reverse();
    println!("Reversed: {:?}", list.to_vec());

    // 3. Stack
    println!("\n--- 3. Stack ---");
    let mut stack = Stack::new();
    stack.push(1);
    stack.push(2);
    stack.push(3);
    println!("Stack push: 1, 2, 3");
    while let Some(value) = stack.pop() {
        println!("Popped: {}", value);
    }

    // 4. Queue
    println!("\n--- 4. Queue ---");
    let mut queue = Queue::new();
    queue.enqueue(1);
    queue.enqueue(2);
    queue.enqueue(3);
    println!("Queue enqueue: 1, 2, 3");
    while let Some(value) = queue.dequeue() {
        println!("Dequeued: {}", value);
    }

    // 5. Merge sorted lists
    println!("\n--- 5. Merge Sorted Lists ---");
    let mut list1 = LinkedList::new();
    list1.push_back(1);
    list1.push_back(3);
    list1.push_back(5);

    let mut list2 = LinkedList::new();
    list2.push_back(2);
    list2.push_back(4);
    list2.push_back(6);

    let merged = merge_sorted_lists(list1, list2);
    println!("Merged: {:?}", merged.to_vec());

    // 6. Find middle
    println!("\n--- 6. Find Middle Element ---");
    let mut list = LinkedList::new();
    for i in 1..=5 {
        list.push_back(i);
    }
    println!("List: {:?}", list.to_vec());
    println!("Middle: {:?}", find_middle(&list));

    println!("\n=== All Linked List Examples Completed ===");
}

Tools

Tools frequently paired with this sample

Related

Related sample collections

Related

Related workflows

Tool usage guide

Sample-focused context for search and workflow understanding

Overview

Use the first card for indexed data, the second for keys and missing values, and the third for node links. Follow changes to values and structure separately; a printed order is not automatically a promised ordering contract.

Select a code card

Keep test inputs small. These examples explain behavior, not throughput or production memory costs.

Select a code card
CardWhat to inspect
Array/Vector OperationsKeep bounds failures explicit
Hash Map OperationsUpdate a key without growing the map
Linked ListReverse links, not the values

How it works

  1. 1Read the named function on the page and track the stated inputs on paper. These are source-reading exercises, not results produced by a browser runner. Copy only the selected helper into a separate test project if you later want to execute it.

Edge cases & common failures

  • Scope of the examples

    Whole cards may require imports, dependencies and integration fixes. A correct trace of one helper does not certify the complete demonstration. Do not run a full entry point merely to inspect these values.

Examples

1. Keep bounds failures explicit

How to use

In Array/Vector Operations, take create_vector()=[1,2,3,4,5] and trace read_element at indices 4 and 5.

Outcome

Index 4 returns Some(&5); index 5 returns None. get() checks bounds, unlike direct indexing that can panic.

2. Update a key without growing the map

How to use

In Hash Map Operations, start with an empty HashMap, then insert_pair for ("apple",5) and ("apple",10). Trace lookup and the entry count.

Outcome

The value becomes 10 and the map still has one key. Updating the existing key replaces its value rather than creating a second entry; do not infer iteration order.

3. Reverse links, not the values

How to use

In Linked List, create an empty singly linked list. push_back(1); push_back(2); push_back(3). Call reverse(), then inspect to_vec().

Outcome

The sequence changes [1,2,3]→[3,2,1], with three nodes still present. Follow the saved next pointer before each link is reversed; otherwise the rest of the chain would be lost.

Hub

Authorized Webhook Capture and Endpoint Trust Checks

Capture and replay controlled webhook requests, inspect delivery evidence, and check the receiver HTTPS certificate without treating a valid certificate as proof of business trust.

Hub

Web Source Reuse and Publication Audit

Extract source evidence, inspect links and assets, analyze metadata and query strings, and check RSS/Atom and robots.txt before reuse, migration, or release.

Hub

Infer JSON Schema from Samples and Spreadsheets

Derive a reviewable JSON Schema draft from representative JSON samples or XLSX rows, then inspect types, requiredness, nulls, and outliers before treating it as a contract.

Hub

Audio Metadata, Tags, Chapters, and Album Art

Prepare music or podcast files by checking tags, managing artwork, adding chapters, and cleaning delivery metadata.

Home
Tools3215
Samples593
Visualizations472
Viewers103
Hubs239
Tags333
Images, Audio & Video657

Image, audio, and video processing, conversion, and optimization tools

Math, Date & Finance647

Calculators, numerics, date logic, statistics, and finance tools

Design & Color298

Color, layout, graphics, visual styling, and design helper tools

Text & Writing209

Writing, cleanup, formatting, extraction, and text analysis tools

Developer & Web194

Developer utilities, networking, web debugging, and automation helpers

Conversion & Encoding175

Format, file, archive, unit, and encoding conversion tools

Lead Generation Quiz Launch and Contact Handoff
Memorial Drafts: Family Review and Print Handoff
Private Habit Records: Backup, Restore and Sharing Review
Article to X and LinkedIn Drafts: Fact Review and Handoff
Markdown Interactive Deck Review and Offline Handoff

© 2026 Elysia Tools. All rights reserved.

DocsPricingAboutTerms of ServicePrivacy PolicyCookiesContact

Development

JSON to Rust Struct Converter

Convert JSON data into Rust structs with serde Serialize/Deserialize derives, snake_case fields, and serde rename attributes

Media

Chrome Web Store Screenshots Resized

Resize images to Chrome Web Store screenshot dimensions while preserving full content and aspect ratio for extension and app listings

Format Conversion

Web Push RFC 8030 Request + VAPID + RFC 8291 Payload Encryption Encoder

Encode a complete Web Push send: RFC 8291 aes128gcm payload encryption, RFC 8292 VAPID ES256 JWT, RFC 8030 headers, APNs/FCM cross-walk and decrypt round-trip verification.

Web & Internet

Web Search (SearXNG JSON)

Search the web through the s.stdlang.com SearXNG instance and return its JSON response for automation or downstream tools.

Design

Web Font Pairing Lab

Preview a heading + body Google Fonts pairing with weight and line-height controls, and copy a ready-to-paste CSS @import + variables snippet. Curated 22-face registry plus 7 proven pairing presets.

Python

Web Data Structures Python Samples

Web Python data structures examples including array operations, hash tables, and linked lists

TypeScript

Web Data Structures TypeScript Samples

Web TypeScript data structures examples including array operations, hash maps, and linked lists

Rust

Web Cryptography Rust Samples

Web Rust cryptography examples including hash calculation, symmetric encryption, and Base64 encoding

Rust

Web Database Rust Samples

Web Rust database operations examples including SQLite connection, SQL queries, and transactions

Rust

Web Date & Time Rust Samples

Web Rust date and time handling examples including getting current time, formatting, and parsing

Rust

Web Desktop Features Rust Samples

Web Rust desktop-like features examples including file dialogs, message boxes, and system integration