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:
push_back()
Inserts the element at the back of the list.
// Using linked listuse std::collections::LinkedList;fn main() {let mut lst = LinkedList::new();// inserting at the backlst.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// printingprintln!("The List contains {:?}", lst);}
push_front()
Inserts the element at the front of the list.
// Using linked listuse std::collections::LinkedList;fn main() {let mut lst = LinkedList::new();// inserting at the backlst.push_front('b'); //blst.push_front('l'); //l->blst.push_front('u'); //u->l->blst.push_front('f'); //f->u->l->b// printingprintln!("The List contains {:?}", lst);}
clear()
Removes all elements from the list.
// Using linked listuse std::collections::LinkedList;fn main() {let mut lst = LinkedList::new();// inserting at the backlst.push_front('b'); //blst.push_front('l'); //l->blst.push_front('u'); //u->l->blst.push_front('f'); //f->u->l->b// clearing listlst.clear();// printingprintln!("The List contains {:?}", lst);}
is_empty()
Returns true
if there is no element in the list; otherwise, it returns false
.
// Using linked listuse std::collections::LinkedList;fn main() {let mut lst = LinkedList::new();// inserting at the backlst.push_front('b'); //blst.push_front('l'); //l->blst.push_front('u'); //u->l->blst.push_front('f'); //f->u->l->b// printingprintln!("The List is empty: {:?}", lst.is_empty());}
pop_back()
/ pop_front()
These functions are used to retrieve (and remove) an element from the list.
// Using linked listuse std::collections::LinkedList;fn main() {let mut lst = LinkedList::new();// inserting at the backlst.push_front('b'); //blst.push_front('l'); //l->blst.push_front('u'); //u->l->blst.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