Skip to content

Instantly share code, notes, and snippets.

@mitghi
Created August 4, 2021 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitghi/d05e4299513c7b9b16feb63e0e1fe54c to your computer and use it in GitHub Desktop.
Save mitghi/d05e4299513c7b9b16feb63e0e1fe54c to your computer and use it in GitHub Desktop.
Linked List in Rust
use std::fmt;
struct Element<T> {
value: T,
next: Option<Box<Element<T>>>,
}
struct List<T> {
head: Option<Box<Element<T>>>,
}
impl<T> List<T> {
fn new() -> Self {
List { head: None }
}
fn push(&mut self, value: T) {
match &self.head {
Some(_) => {
let newNode = Box::new(Element{value: value, next: self.head.take(),
});
self.head = Some(newNode);
},
_ => self.head = Some(Box::new(Element{value: value, next: None}))
}
}
fn pop(&mut self) -> Option<T> {
self.head.take().map(|node| {
self.head = node.next;
node.value
})
}
fn iter(&self) -> Iter<'_, T> {
return Iter { next: self.head.as_deref() }
}
fn into_iter(self) -> IntoIter<T> {
return IntoIter(self);
}
}
struct IntoIter<T>(List<T>);
struct Iter<'a, T> {
next: Option<&'a Element<T>>,
}
impl<T: std::fmt::Display> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
return self.0.pop();
}
}
impl<'a, T: std::fmt::Display> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.next.map(|node| {
self.next = node.next.as_deref();
return &node.value;
})
}
}
fn main() {
let mut v: List<i64> = List::new();
for n in 1..100 {
v.push(n);
}
v.pop();
v.pop();
for item in v.iter() {
println!("item: {}", item);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment