Remove elements from the LinkedList
Rust Programming Language
Problem
Rust program that demonstrates how to remove elements from a LinkedList.
Input
use std::collections::LinkedList;fn main() {// create a new linked listlet mut list = LinkedList::new();// add some elements to the listlist.push_back("apple");list.push_back("banana");list.push_back("cherry");// print the elements of the listprintln!("LinkedList: {:?}", list);// remove the first element from the listif let Some(first) = list.pop_front() {println!("Removed first element: {}", first);}// remove the last element from the listif let Some(last) = list.pop_back() {println!("Removed last element: {}", last);}// remove the element at a specific indexif let Some(removed) = list.remove(1) {println!("Removed element at index 1: {}", removed);}// print the elements of the list againprintln!("LinkedList (after removing elements): {:?}", list);}{codeBox}
Output
LinkedList: ["apple", "banana", "cherry"]Removed first element: appleRemoved last element: cherryRemoved element at index 1: bananaLinkedList (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.