Web Data Structures Rust Samples

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

💻 Array/Vector Operations rust

🟢 simple ⭐⭐

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

⏱️ 20 min 🏷️ rust, web, data structures
Prerequisites: Basic 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 ===");
}

💻 Hash Map Operations rust

🟡 intermediate ⭐⭐⭐

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

⏱️ 25 min 🏷️ rust, web, data structures, hashmap
Prerequisites: Basic Rust, std::collections
// 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)
}

/// 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 ===");
}

💻 Linked List rust

🟡 intermediate ⭐⭐⭐⭐

Implement and use singly and doubly linked lists in Rust

⏱️ 30 min 🏷️ rust, web, data structures, linked list
Prerequisites: Intermediate Rust, ownership, Box, references
// 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(),
        });

        match new_node.next {
            Some(ref mut next) => {
                next.prev = Some(&mut *new_node as *mut _);
            }
            None => {
                self.tail = Some(&mut *new_node as *mut _);
            }
        }

        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 (maintains circular nature)
    fn insert(&mut self, value: i32) {
        let new_node = Box::new(ListNode::new(value));

        match self.head {
            None => {
                new_node.next = Some(new_node);
                self.head = Some(new_node);
            }
            Some(ref mut head) => {
                new_node.next = Some(head);
                // Find last node
                let mut current = &mut head.next;
                while let Some(node) = current {
                    if node.next.as_ref().map(|n| n.value == head.value).unwrap_or(false) {
                        node.next = Some(new_node);
                        break;
                    }
                    current = &mut node.next;
                }
            }
        }
        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 ===");
}