Complete the code to create a circular linked list node that points to itself.
let node = Node { value: 10, next: [1] };In a circular linked list, the node's next pointer points back to itself, creating a loop. Using Some(Box::new(node)) achieves this self-reference.
Complete the code to traverse a circular linked list once starting from head.
let mut current = &head;
loop {
println!("{}", current.value);
current = current.next.as_ref().unwrap();
if current as *const _ == [1] as *const _ {
break;
}
}To stop after one full circle, compare the current node's pointer to the head's pointer. When they match, the loop ends.
Fix the error in the code that inserts a new node after the head in a circular linked list.
let new_node = Box::new(Node { value: 20, next: head.next.take() });
head.next = Some([1]);We assign the new node itself to head.next to insert it after head. Using new_node.next would be incorrect.
Fill both blanks to complete the function that checks if a circular linked list contains a value.
fn contains(head: &Node, target: i32) -> bool {
let mut current = head;
loop {
if current.value == [1] {
return true;
}
current = current.next.as_ref().unwrap();
if current as *const _ == [2] as *const _ {
break;
}
}
false
}The function compares each node's value to the target. It stops when it loops back to the head node.
Fill all three blanks to create a circular linked list from a vector of values.
fn create_circular_list(values: Vec<i32>) -> Option<Box<Node>> {
if values.is_empty() {
return None;
}
let mut head = Box::new(Node { value: values[0], next: None });
let mut current = &mut head;
for &val in &values[1..] {
current.next = Some(Box::new(Node { value: val, next: None }));
current = current.next.as_mut().unwrap();
}
current.next = Some([1]);
Some(head)
}To make the list circular, the last node's next points back to the head node.
