﻿ Rust Program: Insert elements in singly linked list (End)

# 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
}

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

// 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 the list is empty, update the head pointer to point to the new node
return;
}

// Find the last node in the linked list
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

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

}
```
```

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.

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:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿