Skip to content

Instantly share code, notes, and snippets.

@codesections
Created December 23, 2018 15:57
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 codesections/fe22e71f1d993c9aceeb869cf0e5ecce to your computer and use it in GitHub Desktop.
Save codesections/fe22e71f1d993c9aceeb869cf0e5ecce to your computer and use it in GitHub Desktop.
Linked List with a struct
struct LinkedList {
value: u8,
next: Option<Box<LinkedList>>,
}
impl LinkedList {
fn new(value: u8) -> LinkedList {
LinkedList { value, next: None }
}
fn prepend(self, value: u8) -> LinkedList {
LinkedList {
value,
next: Some(Box::new(self)),
}
}
fn len(&self) -> u32 {
match &self.next {
None => 1,
Some(next) => next.len() + 1,
}
}
fn stringify(&self) -> String {
match &self.next {
Some(next) => format!("{} -> {}", self.value, next.stringify()),
None => format!("{}", self.value),
}
}
}
fn main() {
// Create an empty linked list
let mut linked_list = LinkedList::new(1);
// Prepend some elements
linked_list = linked_list.prepend(2);
linked_list = linked_list.prepend(3);
// Show the final state of the list
println!("linked_list has length: {}", linked_list.len());
println!("{}", linked_list.stringify());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment