Exemples de Structures de Données Web Rust
Exemples de structures de données Web Rust incluant les opérations de tableau, hashmap et listes chaînées
Key Facts
- Category
- Rust
- Items
- 3
- Format Families
- sample
Sample Overview
Exemples de structures de données Web Rust incluant les opérations de tableau, hashmap et listes chaînées This sample set belongs to Rust and can be used to test related workflows inside Elysia Tools.
💻 Opérations de Tableau/Vecteur rust
🟢 simple
⭐⭐
Manipulation de vecteur incluant les opérations CRUD, le tri, la recherche et les 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 ===");
}
💻 Opérations HashMap rust
🟡 intermediate
⭐⭐⭐
Utilisation de HashMap pour le stockage et la récupération clé-valeur avec diverses opérations
⏱️ 25 min
🏷️ rust, web, data structures, hashmap
Prerequisites:
Basic Rust, std::collections
💻 Listes Chaînées rust
🟡 intermediate
⭐⭐⭐⭐
Implémenter et utiliser des listes chaînées simples et doubles en 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(),
});
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 ===");
}