3. What is the output linked list after deleting the node at position 2 (0-based) from this list: 10 -> 20 -> 30 -> 40 -> null?
fn main() {
let mut head = Some(Box::new(Node { data: 10, next: Some(Box::new(Node { data: 20, next: Some(Box::new(Node { data: 30, next: Some(Box::new(Node { data: 40, next: None })) })) })) }));
delete_at_position(&mut head, 2);
print_list(&head);
}
fn delete_at_position(head: &mut Option, pos: usize) {
if pos == 0 {
*head = head.as_mut().and_then(|node| node.next.take());
return;
}
let mut current = head.as_mut();
for _ in 0..pos-1 {
if let Some(node) = current {
current = node.next.as_mut();
}
}
if let Some(node) = current {
node.next = node.next.as_mut().and_then(|next_node| next_node.next.take());
}
}
fn print_list(head: &Option) {
let mut current = head;
while let Some(node) = current {
print!("{} -> ", node.data);
current = &node.next;
}
println!("null");
}
struct Node {
data: i32,
next: Option,
}