Rust Program to Remove elements from the LinkedList.


Remove elements from the LinkedList

Rust Programming Language


Remove elements from the LinkedList.


Problem


Rust program that demonstrates how to remove elements from 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);

    // remove the first element from the list
    if let Some(first) = list.pop_front() {
        println!("Removed first element: {}", first);
    }

    // remove the last element from the list
    if let Some(last) = list.pop_back() {
        println!("Removed last element: {}", last);
    }

    // remove the element at a specific index
    if let Some(removed) = list.remove(1) {
        println!("Removed element at index 1: {}", removed);
    }

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

Output


LinkedList: ["apple", "banana", "cherry"]
Removed first element: apple
Removed last element: cherry
Removed element at index 1: banana
LinkedList (after removing elements): []{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 remove the first element from the list, we use the pop_front method, which removes and returns the first element of the list. We then use a if let statement to pattern match the Option returned by pop_front and print the removed element if it exists.

To remove the last element from the list, we use the pop_back method, which is similar to pop_front but removes and returns the last element instead.

To remove an element at a specific index, we use the remove method and pass in the index of the element we want to remove. This removes the element and returns it, and we again use a if let statement to pattern match the Option and print the removed element if it exists.

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


Post a Comment