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