78 lines
1.7 KiB
Rust
78 lines
1.7 KiB
Rust
/// 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<Box<ListItem>>
|
|
}
|
|
|
|
impl ListItem {
|
|
fn new(value: String) -> ListItem {
|
|
ListItem {
|
|
value,
|
|
next: None
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
struct List {
|
|
head: Option<Box<ListItem>>,
|
|
}
|
|
|
|
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<usize> {
|
|
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);
|
|
}
|