Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHESPTRUFRDEEN

Elysia Tools

导航

Rust

Rust 数据结构:序列、查找与节点链接

按序列操作、键查询和节点结构选择示例。

案例

这个案例集合中的条目

代码rust简单

数组/向量操作

向量操作,包括CRUD操作、排序、搜索和转换

难度

4/10

预计时间

20 min

标签

rust, web, data structures

前置条件

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 ===");
}
代码rust中等

哈希表操作

使用HashMap进行键值存储和检索的各种操作

难度

5/10

预计时间

25 min

标签

rust, web, data structures, hashmap

前置条件

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 ===");
}
代码rust中等

链表

在Rust中实现和使用单链表和双链表

难度

7/10

预计时间

30 min

标签

rust, web, data structures, linked list

前置条件

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

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

工具使用指南

帮助搜索与理解工作流的案例说明

概览

第一张卡片适合索引数据,第二张用于键和缺失值,第三张用于节点链接。分别追踪值与结构的变化,不要把一次打印顺序当成顺序保证。

按问题选择代码卡片

使用少量测试输入。这些练习解释行为,不测吞吐量或生产环境内存成本。

按问题选择代码卡片
卡片检查重点
数组/向量操作明确越界结果
哈希表操作更新键但不增加条目
链表反转链接而不是修改数值

使用方式

  1. 1在页面阅读指定函数,把给出的输入逐步记录在纸上。这些是源码阅读练习,不是浏览器运行器产生的结果。以后如需执行,只把选中的帮助函数复制到独立测试项目。

常见失败与 edge cases

  • 示例范围

    整张卡片可能还需要补充导入、依赖和集成修复。一个帮助函数的追踪正确,不代表整个演示已通过验证。不要仅为检查这些数值就运行完整入口。

示例

1. 明确越界结果

如何使用

在《数组/向量操作》取 create_vector()=[1,2,3,4,5],追踪 read_element 的索引 4 和 5。

结果

索引 4 返回 Some(&5),索引 5 返回 None。get() 检查边界,不同于可能 panic 的直接索引。

2. 更新键但不增加条目

如何使用

在《哈希表操作》从空的 HashMap 开始,用 insert_pair 依次写入 ("apple",5)、("apple",10),追踪查询值和条目数。

结果

值变为 10,仍只有一个键。更新现有键是替换值,不是新增第二条;不要由此推断遍历顺序。

3. 反转链接而不是修改数值

如何使用

在《链表》建立空单链表。push_back(1); push_back(2); push_back(3). 调用 reverse(),再查看 to_vec()。

结果

序列从 [1,2,3] 变为 [3,2,1],节点仍为三个。每次反转链接前先保存 next,否则会丢失剩余链条。

专题

数据库 Schema 迁移

通过规范化源数据、审阅结构差异、校验关系并准备回滚资产,规划更安全的数据库迁移。

专题

修复被数据库拒绝的 CSV 导入并完成入库

定位 CSV 导入反复失败的结构原因,把混乱表头对齐到目标表结构,按声明的策略清除重复行,最终产出带类型的 INSERT 语句或供批量装载的 TSV。

专题

图表与图示生成器

根据数据结构选择图表,清晰表达比较、分布、层级、关系、进度和时间安排。

专题

JSON 规范化与数据交换工作流

把结构化来源转换为经过核对的 JSON 表示,再按下游需求导出为表格、配置、文档、API、XML、CSON、EDN、BSON 或 UBJSON。

首页
工具3215
案例593
可视化472
文件查看器103
专题239
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融647

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web194

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

潜客测验发布与联系人交接
讣告、悼词与纪念卡的家属复核及交付
本地习惯记录的备份、恢复演练与分享前检查
长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Development

JSON 转 Rust Struct

将 JSON 数据转换为 Rust struct,含 serde Serialize/Deserialize 派生、snake_case 字段与 serde rename 属性

Media

Chrome网上应用商店截图调整

将图片调整为Chrome网上应用商店截图尺寸,同时保留完整内容和原始宽高比例

Format Conversion

Web Push RFC 8030 请求 + VAPID + RFC 8291 负载加密编码器

编码完整的 Web Push 发送流程:RFC 8291 aes128gcm 负载加密、RFC 8292 VAPID ES256 JWT、RFC 8030 头部、APNs/FCM 头部对照与解密往返验证。

Web & Internet

Web 搜索(SearXNG JSON)

通过 s.stdlang.com 的 SearXNG 实例搜索网页,返回 JSON 结果供自动化或后续工具使用。

Design

网页字体配对实验室

并排预览 标题 + 正文 的 Google 字体配对,调节字重与行高,复制即可粘贴的 CSS @import + 变量代码。精选 22 款字体及 7 组经典搭配预设。

Python

Web Python 数据结构示例

Web Python 数据结构示例,包括数组操作、哈希表和链表

TypeScript

Web TypeScript 数据结构示例

Web TypeScript 数据结构示例,包括数组操作、哈希表和链表

Rust

Web Rust 加密安全示例

Web Rust 加密安全示例,包括哈希计算、对称加密和Base64编码

Rust

Web Rust 数据库操作示例

Web Rust 数据库操作示例,包括SQLite连接、SQL查询和事务处理

Rust

Web Rust 日期时间处理示例

Web Rust 日期时间处理示例,包括获取当前时间、时间格式化和时间解析

Rust

Web Rust 桌面端功能示例

Web Rust 桌面端功能示例,包括文件对话框、消息框和系统集成