diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..29d9341 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "linked-list" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +# Not needed :D diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..460df86 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,77 @@ +/// This is not a very beautiful solution! +/// +/// This was just created for understanding the concept and trying it out. + +#[derive(Debug)] +struct ListItem { + value: String, + next: Option> +} + +impl ListItem { + fn new(value: String) -> ListItem { + ListItem { + value, + next: None + } + } +} + +#[derive(Debug)] +struct List { + head: Option>, +} + +impl List { + /// create an empty list + fn new() -> List { + List { head: None } + } + + /// push a [ListItem] onto the list + fn push(&mut self, item: ListItem) { + let prev_head = self.head.take(); + let mut new_head = Box::new(item); + new_head.next = prev_head; + self.head = Some(new_head); + } + + /// returns None if there is no top item + fn pop(&mut self) -> Option<()> { + // TODO: return removed item + let head = self.head.take(); + self.head = head?.next; + Some(()) + } + + /// Returns None if len > u64 + fn len(&self) -> Option { + let mut num: usize = 0; + if let Some(curr) = &self.head { + // create a mutable reference so we don't actually manipulate the data + let mut curr = curr; + num = num.checked_add(1)?; + while curr.next.is_some() { + curr = curr.next.as_ref().unwrap(); + num = num.checked_add(1)?; + } + } + Some(num) + } +} + +fn main() { + let mut list = List::new(); + + list.push(ListItem::new("Test".to_owned())); + list.push(ListItem::new("Test2".to_owned())); + list.push(ListItem::new("Test3".to_owned())); + + println!("len: {:?}", list.len()); + dbg!(&list); + + list.pop(); + + println!("len: {:?}", list.len()); + dbg!(&list); +}