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

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

## Rust Linked Lists: Exercise-2 with Solution

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

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 front of the linked list
fn insert_front(&mut self, data: T) {
// Create a new node with the given data
let mut new_node = Box::new(Node::new(data));

// Update the next pointer of the new node to point to the current head node

// Update the head pointer to point to the new node
}
}

fn main() {
// Create an empty singly linked list

// Insert elements at the front of the linked list
list.insert_front(3);
list.insert_front(2);
list.insert_front(1);

}
```
```

Output:

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

Explanation:

Here is a brief explanation of the above Rust code:

• Node<T> struct:
• Represents a node in the singly linked list. It contains two fields: data, which stores the data of the node, and 'next', which is an 'Option' containing a pointer to the next node.
• Implementation block for Node<T>: Provides a constructor function "new()" to create a new node with the given data and 'next' set to 'None'.
• Represents a singly linked list with a single field 'head', which is an 'Option' containing a pointer to the head node of the linked list.
• Implementation block for SinglyLinkedList<T>: Provides a constructor function "new()" to create a new empty singly linked list and a method "insert_front()" to insert an element at the front of the linked list.
• In the main() function:
• An empty singly linked list is created.
• Elements are inserted at the front of the linked list using the "insert_front()" method.
• The linked list is printed to visualize its structure.

Rust Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿