Complete the code to create a doubly linked list node with a previous pointer.
struct Node {
value: i32,
next: Option<Box<Node>>,
[1]: Option<Box<Node>>,
}The correct field name for the previous pointer in a doubly linked list node is prev. This is a common convention and keeps the code clear and concise.
Complete the code to move backward in a doubly linked list using the previous pointer.
fn move_backward(node: &Option<Box<Node>>) -> Option<&Box<Node>> {
node.as_ref()?.[1]
}To move backward in a doubly linked list, we use the prev pointer. Since prev is an Option, we call as_ref() to get a reference to the boxed node.
Fix the error in the code to correctly insert a new node after the current node in a doubly linked list.
fn insert_after(current: &mut Box<Node>, value: i32) {
let mut new_node = Box::new(Node {
value,
next: current.next.take(),
[1]: Some(current.clone()),
});
current.next = Some(new_node);
}The new node's previous pointer should be set to prev field pointing to the current node. Using prev is the correct field name.
Fill both blanks to correctly update pointers when removing a node from a doubly linked list.
fn remove_node(node: &mut Box<Node>) {
if let Some(mut next_node) = node.next.take() {
next_node.[1] = node.[2].take();
}
}When removing a node, the next node's previous pointer should be updated to the current node's previous pointer. Both blanks should be filled with prev.
Fill all three blanks to create a map of node values to their previous node values in a doubly linked list.
let map = nodes.iter().map(|node| {
(node.value, node.[1].as_ref().map(|n| n.[2]).unwrap_or([3]))
}).collect::<std::collections::HashMap<_, _>>();To map each node's value to its previous node's value, use the prev pointer, then access the value field of that node. If there is no previous node, use 0 as default.
