2022-12-11 02:27:33 +00:00
|
|
|
use std::fmt::Debug;
|
2022-12-04 01:38:56 +00:00
|
|
|
use std::rc::Rc;
|
|
|
|
|
2022-12-04 05:02:15 +00:00
|
|
|
#[derive(Debug)]
|
2022-12-04 01:38:56 +00:00
|
|
|
pub struct List<T> {
|
|
|
|
head: Option<Rc<Node<T>>>,
|
|
|
|
}
|
|
|
|
|
2022-12-04 05:02:15 +00:00
|
|
|
impl<T> Clone for List<T> {
|
|
|
|
fn clone(&self) -> Self {
|
|
|
|
List {
|
|
|
|
head: self.head.clone(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-04 02:35:30 +00:00
|
|
|
#[derive(Debug, Clone)]
|
2022-12-04 01:38:56 +00:00
|
|
|
pub struct Node<T> {
|
|
|
|
data: T,
|
|
|
|
parent: Option<Rc<Node<T>>>,
|
|
|
|
}
|
|
|
|
|
2022-12-11 02:27:33 +00:00
|
|
|
// TODO: This Debug is only needed because of the try_unwrap+expect
|
|
|
|
impl<T: Debug> List<T> {
|
2022-12-04 01:38:56 +00:00
|
|
|
pub fn new() -> Self {
|
|
|
|
List { head: None }
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn push_front(&self, data: T) -> List<T> {
|
|
|
|
List {
|
|
|
|
head: Some(Rc::new(Node {
|
|
|
|
data: data,
|
|
|
|
parent: self.head.clone(),
|
|
|
|
})),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-11 02:27:33 +00:00
|
|
|
pub fn pop_front(self) -> (Option<T>, List<T>) {
|
|
|
|
match self.head {
|
|
|
|
None => (None, List::new()),
|
|
|
|
Some(popped_node) => {
|
|
|
|
let extracted_node =
|
|
|
|
Rc::try_unwrap(popped_node).expect("TODO I should handle this better");
|
|
|
|
(
|
|
|
|
Some(extracted_node.data),
|
|
|
|
List {
|
|
|
|
head: extracted_node.parent,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-04 03:12:13 +00:00
|
|
|
pub fn without_front(&self) -> List<T> {
|
|
|
|
List {
|
2022-12-04 05:02:15 +00:00
|
|
|
head: self.head.as_ref().map(|node| node.parent.clone()).flatten(),
|
2022-12-04 03:12:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-04 02:06:04 +00:00
|
|
|
pub fn get_data(&self) -> Option<&T> {
|
2022-12-04 02:50:06 +00:00
|
|
|
self.head.as_ref().map(|rc_node| &rc_node.data)
|
2022-12-04 01:38:56 +00:00
|
|
|
}
|
2022-12-04 03:12:13 +00:00
|
|
|
|
|
|
|
pub fn is_empty(&self) -> bool {
|
|
|
|
self.head.is_none()
|
|
|
|
}
|
2022-12-04 01:38:56 +00:00
|
|
|
}
|