w3resource

Rust Program: Inserting elements at the end of a singly linked list

Rust Linked Lists: Exercise-3 with Solution

Write a Rust program to insert elements into a singly linked list at the end.

Sample Solution:

Rust Code:

// Define a struct representing a node in the singly linked list
#[derive(Debug)]
struct Node<T> {
    data: T,                      // Data stored in the node
    next: Option<Box<Node<T>>>,  // Pointer to the next node
}

// Define an implementation for the Node struct
impl<T> Node<T> {
    // Constructor function to create a new node
    fn new(data: T) -> Self {
        Node { data, next: None }
    }
}

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

// Define an implementation for the SinglyLinkedList struct
impl<T> SinglyLinkedList<T> {
    // Constructor function to create a new empty singly linked list
    fn new() -> Self {
        SinglyLinkedList { head: None }
    }

    // Function to insert an element at the end of the linked list
    fn insert_end(&mut self, data: T) {
        // Create a new node with the given data
        let mut new_node = Box::new(Node::new(data));

        // Check if the list is empty
        if self.head.is_none() {
            // If the list is empty, update the head pointer to point to the new node
            self.head = Some(new_node);
            return;
        }

        // Find the last node in the linked list
        let mut current_node = self.head.as_mut().unwrap();
        while let Some(ref mut next_node) = current_node.next {
            current_node = next_node;
        }

        // Insert the new node at the end of the linked list
        current_node.next = Some(new_node);
    }
}

fn main() {
    // Create an empty singly linked list
    let mut list: SinglyLinkedList<i32> = SinglyLinkedList::new();

    // Insert elements at the end of the linked list
    list.insert_end(1);
    list.insert_end(2);
    list.insert_end(3);

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

Output:

Linked List: Some(Node { data: 1, next: Some(Node { data: 2, next: Some(Node { data: 3, next: None }) }) })

Explanation:

The above Rust code defines a singly linked list data structure with two structs: 'Node' and SinglyLinkedList.

  • 'Node' represents a node in the linked list, containing data of generic type 'T' and a pointer to the next node.
  • 'SinglyLinkedList' represents the linked list itself, with a pointer to the head node.

The implementation provides methods to create a new node (Node::new) and a new empty linked list (SinglyLinkedList::new).

The main functionality is demonstrated in the "insert_end()" method of 'SinglyLinkedList', which inserts elements at the end of the linked list. It traverses the list to find the last node and then appends the new node to it.

The "main()" function demonstrates how to use the 'SinglyLinkedList' to create an empty list, insert elements at the end, and print the resulting list.

Rust Code Editor:

Previous: Rust Program: Inserting elements at the front of a singly linked list.
Next: Rust Set Union Function.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.