Skip to content

Instantly share code, notes, and snippets.

@mitghi
Created August 4, 2021 15:22
Show Gist options
  • Save mitghi/8fa71ec672056586e57f2d8048cc693e to your computer and use it in GitHub Desktop.
Save mitghi/8fa71ec672056586e57f2d8048cc693e 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> where T: std::fmt::Display {
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;
return node.value;
});
return None;
}
fn print_items(&self) {
let mut item = self.head.as_ref();
while let Some(mut v) = item {
println!("{}", v.value);
item = v.next.as_ref();
}
}
}
impl<T> fmt::Display for Element<T> where T : fmt::Display{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,"{}", self.value)
}
}
fn main() {
let mut v: List<i64> = List::new();
for n in 1..100 {
v.push(n);
}
v.pop();
v.pop();
v.print_items();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment