Skip to content

Instantly share code, notes, and snippets.

@carlosgrillet
Created March 20, 2026 19:45
Show Gist options
  • Select an option

  • Save carlosgrillet/8c6a05212c2bbbe802cb2881b1484280 to your computer and use it in GitHub Desktop.

Select an option

Save carlosgrillet/8c6a05212c2bbbe802cb2881b1484280 to your computer and use it in GitHub Desktop.
Linked list, but is Rust so nobody can read it.
use std::fmt;
struct Node<T> {
value: T,
next: Option<Box<Node<T>>>,
}
pub struct List<T> {
head: Option<Box<Node<T>>>,
len: usize,
}
impl<T> List<T> {
pub fn new() -> Self {
List { head: None, len: 0 }
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn push_front(&mut self, value: T) {
let old_head = self.head.take();
self.head = Some(Box::new(Node {
value,
next: old_head,
}));
self.len += 1;
}
pub fn pop_front(&mut self) -> Option<T> {
self.head.take().map(|node| {
self.head = node.next;
self.len -= 1;
node.value
})
}
pub fn peek(&self) -> Option<&T> {
self.head.as_ref().map(|node| &node.value)
}
pub fn iter(&self) -> Iter<'_, T> {
Iter {
current: self.head.as_deref(),
}
}
}
impl<T> Default for List<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> Drop for List<T> {
fn drop(&mut self) {
// Iteratively drop nodes to avoid stack overflow on deep lists.
let mut current = self.head.take();
while let Some(mut node) = current {
current = node.next.take();
}
}
}
pub struct Iter<'a, T> {
current: Option<&'a Node<T>>,
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.current.map(|node| {
self.current = node.next.as_deref();
&node.value
})
}
}
impl<'a, T> IntoIterator for &'a List<T> {
type Item = &'a T;
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<T: fmt::Display> fmt::Display for List<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut current = self.head.as_deref();
while let Some(node) = current {
write!(f, "{}", node.value)?;
current = node.next.as_deref();
if current.is_some() {
write!(f, " -> ")?;
}
}
Ok(())
}
}
fn main() {
let mut list: List<i32> = List::new();
for i in 1..=5 {
list.push_front(i);
}
println!("list: {}", list); // 5 -> 4 -> 3 -> 2 -> 1
println!("len: {}", list.len()); // 5
println!("peek: {:?}", list.peek()); // Some(5)
// Works naturally in a for loop because of IntoIterator.
let sum: i32 = list.iter().sum();
println!("sum: {}", sum); // 15
let doubled: Vec<i32> = list.iter().map(|x| x * 2).collect();
println!("doubled: {:?}", doubled); // [10, 8, 6, 4, 2]
println!("popped: {:?}", list.pop_front()); // Some(5)
println!("list: {}", list); // 4 -> 3 -> 2 -> 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment