JUHU
This commit is contained in:
parent
bb74833d4f
commit
d53d575443
9
Cargo.toml
Normal file
9
Cargo.toml
Normal file
|
@ -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
|
77
src/main.rs
Normal file
77
src/main.rs
Normal file
|
@ -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<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);
|
||||||
|
}
|
Loading…
Reference in a new issue