Access elements from a LinkedList
Rust Programming Language
Problem
Rust program that demonstrates how to access 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);// access the first element of the listif let Some(first) = list.front() {println!("First element: {}", first);}// access the last element of the listif let Some(last) = list.back() {println!("Last element: {}", last);}// access the second element of the listif let Some(second) = list.iter().nth(1) {println!("Second element: {}", second);}}{codeBox}
Output
LinkedList: ["apple", "banana", "cherry"]First element: appleLast element: cherrySecond element: banana{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 access the first element of the list, we use the front method, which returns an Option containing a reference to the first element. We then use a if let statement to pattern match the Option and print the first element if it exists.
To access the last element of the list, we use the back method, which is similar to front but returns a reference to the last element instead. Again, we use a if let statement to pattern match the Option and print the last element if it exists.
To access the second element of the list, we use the iter method to create an iterator over the elements of the list, and then use the nth method to access the element at index 1 (since Rust uses zero-based indexing). We then use a if let statement to pattern match the Option and print the second element if it exists.