Created
March 14, 2024 14:37
-
-
Save orzklv/1a9fbf57c806382dd079f4a4cda9bc8c to your computer and use it in GitHub Desktop.
Linked List implementation on 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::mem; | |
pub struct List<T> { | |
head: Link<T>, | |
} | |
type Link<T> = Option<Box<Node<T>>>; | |
struct Node<T> { | |
elem: T, | |
next: Link<T>, | |
} | |
impl<T> List<T> { | |
pub fn new() -> Self { | |
List { head: None } | |
} | |
pub fn push(&mut self, elem: T) { | |
let new_node = Box::new(Node { | |
elem, | |
next: self.head.take(), | |
}); | |
self.head = Some(new_node); | |
} | |
pub fn pop(&mut self) -> Option<T> { | |
self.head.take().map(|node| { | |
self.head =node.next; | |
node.elem | |
}) | |
} | |
} | |
impl<T> Drop for List<T> { | |
fn drop(&mut self) { | |
let mut cur_link = mem::replace(&mut self.head, None); | |
while let Some(mut boxed_node) = cur_link { | |
cur_link = mem::replace(&mut boxed_node.next, None); | |
} | |
} | |
} | |
fn main() { | |
let mut list = List::new(); | |
list.push(1); | |
list.push(2); | |
list.push(3); | |
println!("{:?}", list.pop()); // Some(3) | |
println!("{:?}", list.pop()); // Some(2) | |
println!("{:?}", list.pop()); // Some(1) | |
println!("{:?}", list.pop()); // None | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment