Complete the code to create a new node in a linked list.
struct Node {
value: i32,
next: Option<Box<Node>>,
};
impl Node {
fn new(value: i32) -> Self {
Node {
value: value,
next: [1],
}
}
}When creating a new node, its next pointer should be None because it does not point to any other node yet.
Complete the code to add a new node at the beginning of the linked list.
fn prepend(head: Option<Box<Node>>, value: i32) -> Option<Box<Node>> {
Some(Box::new(Node {
value: value,
next: [1],
}))
}The new node's next pointer should point to the current head of the list.
Fix the error in the code to traverse and print all values in the linked list.
fn print_list(mut head: &Option<Box<Node>>) {
while let Some(node) = [1] {
println!("{}", node.value);
head = &node.next;
}
}Use head.as_ref() to get a reference to the node inside the Option without taking ownership.
Fill both blanks to create a linked list with values 1, 2, 3 in order.
let mut list = [1]; list = prepend(list, 3); list = prepend(list, [2]); list = prepend(list, 1);
Start with an empty list None, then prepend 3, then 2, then 1 to get 1 -> 2 -> 3.
Fill all three blanks to create a function that counts nodes in the linked list.
fn count_nodes(mut head: &Option<Box<Node>>) -> i32 {
let mut count = 0;
while let Some(node) = [1] {
count += [2];
head = &[3];
}
count
}Use head.as_ref() to borrow the node, increment count by 1, and move to node.next to traverse.
