This Rust program uses the LinkedList, and shows how to add and remove elements from the LinkedList. It uses append() which combines 2 LinkedLists efficiently.
use std::collections::*;
fn main() {
// Part 1: create new LinkedList and use push_back to add elements.
let mut k = LinkedList::new();
k.push_back(500);
k.push_back(200);
k.push_back(0);
println!(
"push_back: {:?}", k);
// Part 2: use push_front to add an element to the start.
k.push_front(-100);
println!(
"push_front: {:?}", k);
// Part 3: use pop_back and pop_front to remove 1 element from the end and start.
k.pop_back();
k.pop_front();
println!(
"pop_back, pop_front: {:?}", k);
// Part 4: create a second LinkedList, and append it to the first.
let mut k2 = LinkedList::from([1000, 2000, 3000]);
k.append(&mut k2);
// Part 5: loop over elements in the LinkedList and print them.
for element in k {
println!(
"Element: {element}");
}
}
push_back: [500, 200, 0]
push_front: [-100, 500, 200, 0]
pop_back, pop_front: [500, 200]
Element: 500
Element: 200
Element: 1000
Element: 2000
Element: 3000