LinkedList in Rust

Overview

The LinkedList in Rust is a data structure that provides a way to store a sequence of elements, where each element points to the next one, forming a chain. This structure is particularly useful when you need to frequently insert or remove elements from the middle of the list, as it can be more efficient than using a Vec in such cases.

Implementation

Basic Structure

The LinkedList is implemented using a ListItem struct that holds the data and a pointer to the next item. The LinkedList itself maintains a pointer to the head of the list.

use std::cell::RefCell;
use std::rc::Rc;

type ItemData<T> = Rc<RefCell<T>>;
type ListItemPtr<T> = Rc<RefCell<ListItem<T>>>;

struct ListItem<T> {
    data: ItemData<T>,
    next: Option<ListItemPtr<T>>,
}

impl<T> ListItem<T> {
    fn new(t: T) -> Self {
        Self {
            data: Rc::new(RefCell::new(t)),
            next: None,
        }
    }
}

struct LinkedList<T> {
    head: ListItemPtr<T>,
}

impl<T> LinkedList<T> {
    fn new(t: T) -> Self {
        Self {
            head: Rc::new(RefCell::new(ListItem::new(t))),
        }
    }
}

Enhanced Implementation with Documentation

To make the LinkedList more idiomatic and consistent with other Rust collections like Vec, the LinkedList is updated to allow for an empty list and includes documentation.

/// Provides a singly linked list implementation with iterator access.
pub struct LinkedList<T> {
    head: Option<ListItemPtr<T>>,
}

impl<T> LinkedList<T> {
    /// Constructs a new, empty [`LinkedList<T>`].
    pub fn new() -> Self {
        Self { head: None }
    }
    /// Appends an element to the end of the list. If the list is empty,
    /// the element becomes the first element of the list.
    pub fn append(&mut self, t: T) {
        match &self.head {
            Some(head) => {
                let mut next = head.clone();
                while next.as_ref().borrow().next.is_some() {
                    let n = next.as_ref().borrow()
                        .next.as_ref().unwrap().clone();
                    next = n;
                }
                next.as_ref().borrow_mut().next =
                    Some(Rc::new(RefCell::new(ListItem::new(t))));
            }
            None => {
                self.head = Some(Rc::new(RefCell::new(ListItem::new(t))));
            }
        }
    }
    /// Returns an iterator over the list.
    pub fn iter(&self) -> Iter<T> {
        Iter {
            next: self.head.clone(),
            data: None,
            phantom: PhantomData,
        }
    }
    /// Returns an iterator over the list that allows mutation.
    pub fn iter_mut(&mut self) -> IterMut<T> {
        IterMut {
            next: self.head.clone(),
            data: None,
            phantom: PhantomData,
        }
    }
    /// Consumes this list returning an iterator over its values.
    pub fn into_iter(self) -> IntoIter<T> {
        IntoIter {
            next: self.head.clone(),
        }
    }
}

Cloning

The LinkedList can be cloned using the Clone trait. The clone_from method is used within the clone method to efficiently copy elements from one list to another.

impl<T: Clone> Clone for LinkedList<T> {
    fn clone(&self) -> Self {
        let mut cloned = Self::new();
        cloned.clone_from(self);
        cloned
    }
    fn clone_from(&mut self, source: &Self) {
        self.head = None;
        source.iter().for_each(|item| {
            self.append(item.clone())
        });
    }
}

Documentation and Testing

The LinkedList crate includes top-level documentation and examples, which are automatically tested using Rust's rustdoc. This ensures that the examples are always up-to-date and functional.

//! # linkedlist crate
//!
//! This crate provides a simple linked list implementation.
//!
//! The crate serves as a teaching example for the book [_Rust Advanced
//! Techniques_](https://www.manning.com/books/idiomatic-rust).
//!
//! ## Example usage
//!
//! ```rust
//! use linkedlist::LinkedList;
//!
//! let mut animals = LinkedList::new();
//! animals.append("chicken");
//! animals.append("ostrich");
//! animals.append("antelope");
//! animals.append("axolotl");
//! animals.append("okapi");
//! ```

Benchmarking

The performance of the LinkedList can be compared to other data structures like Vec and HashSet using benchmarks. This helps in understanding the trade-offs involved in using different data structures for specific tasks.

#[bench]
fn vec_append(b: &mut Bencher) {
    b.iter(|| {
        let mut nums: Vec<i32> = Vec::new();
        for n in 0..1_000_000 {
            nums.push(n);
        }
    });
}

#[bench]
fn list_append(b: &mut Bencher) {
    b.iter(|| {
        let mut nums: LinkedList<i32> = LinkedList::new();
        for n in 0..1_000_000 {
            nums.push_back(n);
        }
    });
}

#[bench]
fn set_append(b: &mut Bencher) {
    b.iter(|| {
        let mut nums: HashSet<i32> = HashSet::new();
        for n in 0..1_000_000 {
            nums.insert(n);
        }
    });
}

Figures

The documentation for the LinkedList crate is visually represented in several figures, showing the progression from an empty documentation to a fully documented crate.

Figure 6.3 linkedlist crate with top-level documentation Figure 6.3 linkedlist crate with top-level documentation

Figure 6.4 Documented LinkedList Figure 6.4 Documented LinkedList

FAQ (Frequently asked questions)