Rust Program: Deleting Node from singly linked list
Write a Rust program to delete a node from a singly linked list by value.
Sample Solution:
Rust Code:
#[derive(Debug)] // Add this line to implement Debug for LinkedList
struct Node {
    v: usize,
    next: Option<Box<Node>>,
}
struct LinkedList {
    head: Option<Box<Node>>,
}
impl LinkedList {
    fn remove(&mut self, v: usize) -> Option<usize> {
        let mut current = &mut self.head;
        loop {
            match current {
                None => return None,
                Some(node) if node.v == v => {
                    *current = node.next.take();
                    return Some(v);
                },
                Some(node) => {
                    current = &mut node.next;
                }
            }
        }
    }
}
fn main() {
    let mut list = LinkedList {
        head: Some(Box::new(Node {
            v: 10,
            next: Some(Box::new(Node {
                v: 20,
                next: Some(Box::new(Node {
                    v: 30,
                    next: None,
                })),
            })),
        })),
    };
     println!("Original Linked List: {:?}", list.head);
    // Remove node with value 20
    if let Some(deleted_value) = list.remove(20) {
        println!("Deleted node with value: {}", deleted_value);
    } else {
        println!("Node not found.");
    }
    // Print updated linked list
   println!("Updated Linked List: {:?}", list.head);
}
Output:
Original Linked List: Some(Node { v: 10, next: Some(Node { v: 20, next: Some(Node { v: 30, next: None }) }) })
Deleted node with value: 20
Updated Linked List: Some(Node { v: 10, next: Some(Node { v: 30, next: None }) })
Explanation:
The above Rust code defines a singly linked list data structure (LinkedList) and its associated methods. Each node in the linked list (Node) holds a value of type "usize" and a pointer to the next node.
- The "remove()" method in the "LinkedList" implementation removes the first occurrence of a node with a given value (v) from the linked list.
 - The "main()" function demonstrates the usage of the "LinkedList" by creating a linked list with some nodes and then removing a node with a specific value (20 in this case).
 - It prints the original linked list, the value of the deleted node (if found), and the updated linked list after the removal operation.
 
Go to:
PREV : Rust Program: Inserting elements at the end of a singly linked list.
NEXT : Rust Set Union Function.
Rust Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
