w3resource

Rust Program: Deleting Node by position from singly linked list

Rust Linked Lists: Exercise-5 with Solution

Write a Rust program to delete a node from a singly linked list by position.

Sample Solution:

Rust Code:

// Define the Node struct to represent individual nodes in the linked list
#[derive(Debug)]
struct Node<T> {
    data: T,
    next: Option<Box<Node<T>>>, // Pointer to the next node
}

// Define the SinglyLinkedList struct to represent the linked list
struct SinglyLinkedList<T> {
    head: Option<Box<Node<T>>>, // Pointer to the head of the linked list
}

impl<T> SinglyLinkedList<T> {
    // Method to delete a node from the linked list by position
    fn delete_node_by_position(&mut self, position: usize) {
        let mut current = &mut self.head; // Mutable reference to the head of the linked list
        let mut count = 0; // Initialize a counter to keep track of the current position

        // Traverse the linked list
        while let Some(node) = current {
            // Check if the current node is the one to be deleted
            if position == 0 {
                // If the first node is to be deleted, update the head to the next node
                self.head = node.next.take();
                return; // Exit the function
            }

            // Check if the next node exists and is at the position to be deleted
            if count == position - 1 {
                // If the next node is to be deleted, update the next pointer of the current node
                node.next = node.next.take().unwrap().next;
                return; // Exit the function
            }

            // Move to the next node
            current = &mut node.next;
            count += 1; // Increment the counter
        }
    }
}

fn main() {
    // Create a new linked list
    let mut list = SinglyLinkedList {
        head: Some(Box::new(Node { data: 1, next: None })),
    };

    // Insert some nodes into the linked list
    list.head = Some(Box::new(Node { data: 2, next: list.head.take() }));
    list.head = Some(Box::new(Node { data: 3, next: list.head.take() }));
    list.head = Some(Box::new(Node { data: 4, next: list.head.take() }));
    list.head = Some(Box::new(Node { data: 5, next: list.head.take() }));

    // Print the original linked list
    println!("Original Linked List: {:?}", list.head);

    // Delete a node from the linked list by position
    list.delete_node_by_position(2); // Delete node at position 2 (3rd node)

    // Print the updated linked list
    println!("Linked List after deletion: {:?}", list.head);
}

Output:

Original Linked List: Some(Node { data: 5, next: Some(Node { data: 4, next: Some(Node { data: 3, next: Some(Node { data: 2, next: Some(Node { data: 1, next: None }) }) }) }) })
Linked List after deletion: Some(Node { data: 5, next: Some(Node { data: 4, next: Some(Node { data: 2, next: Some(Node { data: 1, next: None }) }) }) })

Explanation:

Here is a brief explanation of the above Rust code:

  • Node struct: Represents individual nodes in the linked list. Each node contains data (data) and a pointer to the next node (next), which is an 'Option' wrapping a 'Box' pointing to another 'Node'.
  • SinglyLinkedList struct: Represents the linked list itself. It contains a pointer to the head of the linked list (head), which is an 'Option' wrapping a 'Box' pointing to the first Node.
  • impl block for SinglyLinkedList: Implements methods for the linked list. In this case, it defines a method "delete_node_by_position()" to remove a node from the linked list by its position.
  • delete_node_by_position method: Removes a node from the linked list based on its position. It traverses the list until it reaches the specified position, then adjusts the pointers to bypass the node to be deleted.
  • main function: Entry point of the program. It shows the usage of the linked list by creating a list, inserting nodes, deleting a node by position, and printing the original and updated lists.

Rust Code Editor:

Previous: Rust Program: Deleting Node from singly linked list.
Next: Rust Program: Reversing singly linked list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/rust/collections_and_data_structures/rust-linked-lists-exercise-5.php