Created
August 4, 2021 15:22
-
-
Save mitghi/8fa71ec672056586e57f2d8048cc693e to your computer and use it in GitHub Desktop.
Linked List in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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