Mental Model
A node holds data and a pointer to the next node, linking pieces like train cars.
Analogy: Imagine a train where each car carries a box (data) and hooks to the next car (pointer).
Node1[data] -> Node2[data] -> Node3[data] -> null
Node1[data] -> Node2[data] -> Node3[data] -> null
[10 | null]
[10 | null] [20 | null]
[10 | ->] -> [20 | null]
[10 | ->] -> [20 | null] [30 | null]
[10 | ->] -> [20 | ->] -> [30 | null]
[10 | ->] -> [20 | ->] -> [30 | null]
use std::rc::Rc; use std::cell::RefCell; // Define a Node struct with data and pointer to next node struct Node { data: i32, next: Option<Rc<RefCell<Node>>>, } impl Node { // Create a new node with given data and no next node fn new(data: i32) -> Rc<RefCell<Node>> { Rc::new(RefCell::new(Node { data, next: None })) } } fn main() { // Step 1: Create first node let first = Node::new(10); // Step 2: Create second node let second = Node::new(20); // Step 3: Link first node to second first.borrow_mut().next = Some(second.clone()); // Step 4: Create third node let third = Node::new(30); // Step 5: Link second node to third second.borrow_mut().next = Some(third.clone()); // Print the linked list let mut current = Some(first.clone()); while let Some(node) = current { print!("{} -> ", node.borrow().data); current = node.borrow().next.clone(); } println!("null"); }
fn new(data: i32) -> Rc<RefCell<Node>> {first.borrow_mut().next = Some(second.clone());second.borrow_mut().next = Some(third.clone());while let Some(node) = current {while let Some(node) = current {while let Some(node) = current {next pointer in a singly linked list node structure?next pointernext pointer specifically points to the next node, enabling traversal through the list.next pointer = next node address [OK]next pointer using Option and Box?Box is used to allocate nodes on the heap. The Option type allows for a nullable pointer.Option, so it cannot represent the end of the list (null). struct Node { data: i32, next: Option } correctly uses Option. struct Node { data: i32, next: &Node } uses a reference without lifetime, which is invalid. struct Node { data: i32, next: Option<&Node> } uses a reference inside Option, which is problematic for ownership.struct Node {
data: i32,
next: Option,
}
fn main() {
let node3 = Node { data: 3, next: None };
let node2 = Node { data: 2, next: Some(Box::new(node3)) };
let node1 = Node { data: 1, next: Some(Box::new(node2)) };
let mut current = &node1;
while let Some(ref next_node) = current.next {
println!("{} ->", current.data);
current = next_node;
}
println!("{} -> null", current.data);
}struct Node {
data: i32,
next: Option<Node>,
}Box to know size at compile time.Option<Node> causes infinite size because Node contains Node directly. It must be Option to compile.prev and next nodes without causing ownership or borrowing errors?Rc allowing multiple owners and interior mutability safely.Pass the test and this pattern moves unknown