Complete the code to remove the last node from the doubly linked list.
fn delete_from_end(head: &mut Option<Box<Node>>) {
if head.is_none() {
return;
}
let mut current = head.as_mut();
while let Some(node) = current {
if node.next.is_none() {
node.prev.as_mut().map(|prev| prev.next = None);
[1]
break;
}
current = node.next.as_mut();
}
}The last node is removed by updating the previous node's next pointer to None and taking the head if it's the only node.
Complete the code to update the previous node's next pointer when deleting the last node.
fn delete_from_end(head: &mut Option<Box<Node>>) {
if head.is_none() {
return;
}
let mut current = head.as_mut();
while let Some(node) = current {
if node.next.is_none() {
[1];
break;
}
current = node.next.as_mut();
}
}node.next to None instead of the previous node's next.We update the previous node's next pointer to None to remove the last node from the list.
Fix the error in the code to correctly handle deleting the last node when the list has only one node.
fn delete_from_end(head: &mut Option<Box<Node>>) {
if head.is_none() {
return;
}
let mut current = head.as_mut();
while let Some(node) = current {
if node.next.is_none() {
if node.prev.is_none() {
[1];
} else {
node.prev.as_mut().map(|prev| prev.next = None);
}
break;
}
current = node.next.as_mut();
}
}head = None directly without take().When the list has only one node, we remove it by taking the head, setting it to None.
Fill both blanks to complete the function that deletes the last node and returns its value.
fn delete_from_end(head: &mut Option<Box<Node>>) -> Option<i32> {
if head.is_none() {
return None;
}
let mut current = head.as_mut();
while let Some(node) = current {
if node.next.is_none() {
let val = node.data;
if node.prev.is_none() {
[1];
} else {
node.prev.as_mut().map(|prev| prev.next = None);
}
return Some(val);
}
current = node.next.as_mut();
}
None
}We remove the only node by taking the head and unlink the last node by setting previous node's next to None.
Fill all three blanks to implement a safe delete from end that updates pointers and returns the deleted value.
fn delete_from_end(head: &mut Option<Box<Node>>) -> Option<i32> {
if head.is_none() {
return None;
}
let mut current = head.as_mut();
while let Some(node) = current {
if node.next.is_none() {
let val = node.data;
if node.prev.is_none() {
[1];
} else {
node.prev.as_mut().map(|prev| prev.next = [2]);
}
[3]
}
current = node.next.as_mut();
}
None
}The function removes the last node by taking the head if it's the only node, sets previous node's next to None, and returns the deleted value.
