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 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); }
push_front()
Inserts the element at the front of 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 // printing println!("The List contains {:?}", lst); }
clear()
Removes all elements 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 // clearing list lst.clear(); // printing println!("The List contains {:?}", lst); }
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()); }
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()); }
RELATED TAGS
View all Courses