Rust Program to Convert the LinkedList into an Array and vice versa


Convert the LinkedList into an Array and vice versa

Rust Programming Language


Convert the LinkedList into an Array and vice versa


Problem


In Rust, the equivalent of a LinkedList is a LinkedList type provided by the std::collections module. Here is an example program that demonstrates how to convert a LinkedList into an array and vice versa.

Input


use std::collections::LinkedList;

fn main() {
    // Convert a LinkedList to an Array
    let mut list = LinkedList::new();
    list.push_back(1);
    list.push_back(2);
    list.push_back(3);
    let array: Vec<i32> = list.into_iter().collect();
    println!("{:?}", array);

    // Convert an Array to a LinkedList
    let array = [1, 2, 3];
    let list: LinkedList<i32> = array.iter().cloned().collect();
    println!("{:?}", list);
}{codeBox}

Output


[1, 2, 3]
[1, 2, 3]{codeBox}

Explanation


In this program, we first create a LinkedList of integers and then convert it into a Vec of integers using the into_iter() method and the collect() function. We then print the resulting Vec to the console.

Next, we create an array of integers and then convert it into a LinkedList of integers using the iter() method to create an iterator over the elements, the cloned() method to clone the elements into a new LinkedList, and the collect() function to collect the elements into the LinkedList. We then print the resulting LinkedList to the console.

The first line is the resulting Vec after converting the LinkedList to a Vec of integers using the into_iter() method and collect() function.

The second line is the resulting LinkedList after converting the array to a LinkedList of integers using the iter() method to create an iterator over the elements, the cloned() method to clone the elements into a new LinkedList, and the collect() function to collect the elements into the LinkedList.

Post a Comment