﻿ Rust Program: Creating an empty singly linked list

# Rust Program: Creating an empty singly linked list

## Rust Linked Lists: Exercise-1 with Solution

Write a Rust program to create an empty singly linked list.

Sample Solution:

Rust Code:

``````// Define a struct representing a node in the singly linked list
#[derive(Debug)]  // Add the Debug trait to automatically implement Debug functionality
struct Node<T> {
data: T,          // Data stored in the node
next: Option<Box<Node<T>>>,  // Pointer to the next node, using Option to handle the case of no next node
}

// Define an empty 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 }  // Initialize the node with data and no next node
}
}

// Define a struct representing a singly linked list
}

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

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

// Print the empty list
}
```
```

Output:

```Empty Singly Linked List: None
```

Explanation:

Here is a brief explanation of the above Rust code:

• Node<T> struct:
• Represents a node in the singly linked list.
• It has two fields: 'data' to store the node's value and 'next' to store a pointer to the next node (wrapped in Option<Box<Node<T>>> to handle the case of no next node).
• Implements the 'Debug' trait, which allows printing the node for debugging purposes.
• Provides a constructor function "new()" to create a new node with the given data and no next node.
• Represents a singly linked list.
• It has one field: 'head', which is an Option<Box<Node<T>>> representing the head node of the linked list.
• Provides a constructor function "new()" to create a new empty singly linked list with no head node.
• main() function:
• Creates an empty singly linked list (empty_list) of type SinglyLinkedList<i32> using the new() constructor.
• Prints the empty list, specifically printing the 'head' field of the 'empty_list'.

Rust Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿