Mental Model
Add a new item right at the start so it becomes the first thing in the list.
Analogy: Imagine a line of people waiting. If a new person comes and stands at the very front, everyone else moves back one spot.
head -> 1 -> 2 -> 3 -> null
head -> 1 -> 2 -> 3 -> null
new_node[0] null
new_node[0] -> 1 -> 2 -> 3 -> null
head -> 0 -> 1 -> 2 -> 3 -> null
head -> 0 -> 1 -> 2 -> 3 -> null
use std::rc::Rc; use std::cell::RefCell; #[derive(Debug)] struct Node { val: i32, next: Option<Rc<RefCell<Node>>>, } #[derive(Debug)] struct LinkedList { head: Option<Rc<RefCell<Node>>>, } impl LinkedList { fn new() -> Self { LinkedList { head: None } } fn insert_at_beginning(&mut self, val: i32) { // create new node let new_node = Rc::new(RefCell::new(Node { val, next: self.head.clone() })); // update head to new node self.head = Some(new_node); } fn print_list(&self) { let mut current = self.head.clone(); while let Some(node) = current { print!("{} -> ", node.borrow().val); current = node.borrow().next.clone(); } println!("null"); } } fn main() { let mut list = LinkedList::new(); // initial list 3 -> 2 -> 1 -> null list.insert_at_beginning(3); list.insert_at_beginning(2); list.insert_at_beginning(1); println!("Initial list:"); list.print_list(); // insert 0 at beginning list.insert_at_beginning(0); println!("After inserting 0 at beginning:"); list.print_list(); }
let new_node = Rc::new(RefCell::new(Node { val, next: self.head.clone() }));self.head = Some(new_node);self.head = Some(new_node);
let new_node = Rc::new(RefCell::new(Node { val, next: self.head.clone() }));let mut list = LinkedList::new(); list.insert_at_beginning(10); list.insert_at_beginning(20); list.insert_at_beginning(30); list.print();Assuming print() shows nodes from head to tail.
fn insert_at_beginning(&mut self, data: i32) {
let new_node = Box::new(Node { data, next: self.head });
self.head = Some(new_node);
}Pass the test and this pattern moves unknown