Complete the code to create a new node with the given value.
struct Node {
value: i32,
next: Option<Box<Node>>,
}
impl Node {
fn new(val: i32) -> Self {
Node {
value: val,
next: [1],
}
}
}When creating a new node, its next pointer should be empty, which is represented by None in Rust.
Complete the code to move the slow pointer one step forward in the linked list.
fn move_slow(slow: &Option<Box<Node>>) -> Option<&Box<Node>> {
slow.as_ref().and_then(|node| [1])
}To move the slow pointer one step forward, we get a reference to the next node using node.next.as_ref().
Fix the error in the loop condition to move the fast pointer two steps ahead safely.
while fast.is_some() && fast.as_ref().unwrap().next.[1]() { fast = fast.as_ref().unwrap().next.as_ref().unwrap().next.as_ref(); slow = slow.as_ref().unwrap().next.as_ref(); }
The loop should continue while fast and fast.next exist, so we check is_some() on fast.next.
Fill both blanks to correctly update slow and fast pointers inside the loop.
slow = slow.as_ref().unwrap().next.[1](); fast = fast.as_ref().unwrap().next.as_ref().unwrap().next.[2]();
We use as_ref() to get references to the next nodes without taking ownership.
Fill all three blanks to return the middle node's value safely.
fn find_middle(head: &Option<Box<Node>>) -> Option<i32> {
let mut slow = head.as_ref();
let mut fast = head.as_ref();
while fast.is_some() && fast.as_ref().unwrap().next.[1]() {
slow = slow.unwrap().next.[2]();
fast = fast.unwrap().next.as_ref().unwrap().next.[3]();
}
slow.map(|node| node.value)
}Use as_ref() to get references safely inside the loop condition and pointer updates. This avoids ownership issues and panics.
