What is a linked list in Rust?

A linked list is a data structure made up of a chain of node objects. Each node contains a value and a pointer to the next node in the chain.

In Rust, a linked list is already implemented in the standard collection library. Different built-in methods are shown below:

1. push_back()

Inserts the element at the back of the list.

svg viewer
// Using linked list
use std::collections::LinkedList;
fn main() {
let mut lst = LinkedList::new();
// inserting at the back
lst.push_back('b'); //b->
lst.push_back('l'); //b->l->
lst.push_back('u'); //b->l->u->
lst.push_back('f'); //b->l->u->f
// printing
println!("The List contains {:?}", lst);
}

2.push_front()

Inserts the element at the front of the list.

svg viewer
// Using linked list
use std::collections::LinkedList;
fn main() {
let mut lst = LinkedList::new();
// inserting at the back
lst.push_front('b'); //b
lst.push_front('l'); //l->b
lst.push_front('u'); //u->l->b
lst.push_front('f'); //f->u->l->b
// printing
println!("The List contains {:?}", lst);
}

3.clear()

Removes all elements from the list.

svg viewer
// Using linked list
use std::collections::LinkedList;
fn main() {
let mut lst = LinkedList::new();
// inserting at the back
lst.push_front('b'); //b
lst.push_front('l'); //l->b
lst.push_front('u'); //u->l->b
lst.push_front('f'); //f->u->l->b
// clearing list
lst.clear();
// printing
println!("The List contains {:?}", lst);
}

4. is_empty()

Returns true if there is no element in the list; otherwise, it returns false.

// Using linked list
use std::collections::LinkedList;
fn main() {
let mut lst = LinkedList::new();
// inserting at the back
lst.push_front('b'); //b
lst.push_front('l'); //l->b
lst.push_front('u'); //u->l->b
lst.push_front('f'); //f->u->l->b
// printing
println!("The List is empty: {:?}", lst.is_empty());
}

5. pop_back() / pop_front()

These functions are used to retrieve (and remove) an element from the list.

// Using linked list
use std::collections::LinkedList;
fn main() {
let mut lst = LinkedList::new();
// inserting at the back
lst.push_front('b'); //b
lst.push_front('l'); //l->b
lst.push_front('u'); //u->l->b
lst.push_front('f'); //f->u->l->b
// pop_back()
println!("The element popped from back: {:?}", lst.pop_back());
// pop_front()
println!("The element popped from front: {:?}", lst.pop_front());
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved