Rust Program to Add elements to a LinkedList


Add elements to a LinkedList

Rust Programming Language


Add elements to a LinkedList


Problem


Rust program that demonstrates how to add elements to a LinkedList.

Input


use std::collections::LinkedList;

fn main() {
    // create a new linked list
    let mut list = LinkedList::new();

    // add some elements to the list
    list.push_back("apple");
    list.push_back("banana");
    list.push_back("cherry");

    // print the elements of the list
    println!("LinkedList: {:?}", list);

    // add an element to the front of the list
    list.push_front("orange");

    // print the elements of the list again
    println!("LinkedList (after adding 'orange' to the front): {:?}", list);

    // add an element at a specific index
    list.insert(2, "grape");

    // print the elements of the list again
    println!("LinkedList (after adding 'grape' at index 2): {:?}", list);
}{codeBox}

Output


LinkedList: ["apple", "banana", "cherry"]
LinkedList (after adding 'orange' to the front): ["orange", "apple", "banana", "cherry"]
LinkedList (after adding 'grape' at index 2): ["orange", "apple", "grape", "banana", "cherry"]{codeBox}

Explanation


In this program, we first create a new LinkedList and add some elements to it using the push_back method. We then print the elements of the list using Rust's println! macro and the {:?} format specifier to print the list in debug format.

To add an element to the front of the list, we use the push_front method and pass in the element we want to add as an argument. This inserts the element at the beginning of the list, before all other elements.

To add an element at a specific index, we use the insert method and pass in the index where we want to insert the element, as well as the element itself. In this example, we insert the element "grape" at index 2, which shifts the existing elements "banana" and "cherry" to higher indices.

After each addition, we print the elements of the list again to see the updated contents.

Post a Comment