use std::collections::HashMap;
// Node for linked list
struct Node {
val: i32,
next: Option<Box<Node>>,
}
impl Node {
fn new(val: i32) -> Self {
Node { val, next: None }
}
}
// Linked list lookup function
fn linked_list_lookup(head: &Option<Box<Node>>, target: i32) -> bool {
let mut current = head;
while let Some(node) = current {
if node.val == target {
return true; // found value
}
current = &node.next; // move to next node
}
false // not found
}
fn main() {
// Array lookup
let arr = [1, 2, 3];
let target = 3;
let mut found_in_array = false;
for &val in arr.iter() {
if val == target {
found_in_array = true;
break; // stop when found
}
}
// Linked list setup: 1 -> 2 -> 3
let node3 = Box::new(Node::new(3));
let mut node2 = Box::new(Node::new(2));
node2.next = Some(node3);
let mut node1 = Box::new(Node::new(1));
node1.next = Some(node2);
let head = Some(node1);
let found_in_list = linked_list_lookup(&head, target);
// Hash map lookup
let mut map = HashMap::new();
map.insert(1, 'a');
map.insert(2, 'b');
map.insert(3, 'c');
let found_in_map = map.get(&target);
// Print results
println!("Array contains {}: {}", target, found_in_array);
println!("Linked list contains {}: {}", target, found_in_list);
match found_in_map {
Some(&ch) => println!("Hash map key {} maps to value '{}': true", target, ch),
None => println!("Hash map key {} not found: false", target),
}
}for &val in arr.iter() {
if val == target {
found_in_array = true;
break;
}
}
scan array elements until target found or end reached
while let Some(node) = current {
if node.val == target {
return true;
}
current = &node.next;
}
traverse linked list nodes checking each value
let found_in_map = map.get(&target);
directly access hash map value by key
Array contains 3: true
Linked list contains 3: true
Hash map key 3 maps to value 'c': true