76 lines
1.8 KiB
Rust
76 lines
1.8 KiB
Rust
use std::fmt::Debug;
|
|
use std::rc::Rc;
|
|
|
|
#[derive(Debug)]
|
|
pub struct List<T> {
|
|
head: Option<Rc<Node<T>>>,
|
|
}
|
|
|
|
impl<T> Clone for List<T> {
|
|
fn clone(&self) -> Self {
|
|
List {
|
|
head: self.head.clone(),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct Node<T> {
|
|
data: T,
|
|
parent: Option<Rc<Node<T>>>,
|
|
}
|
|
|
|
// TODO: This Debug is only needed because of the try_unwrap+expect
|
|
impl<T: Debug> List<T> {
|
|
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(),
|
|
})),
|
|
}
|
|
}
|
|
|
|
pub fn pop_front(&mut self) -> (Option<T>, List<T>) {
|
|
match self.head.take() {
|
|
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,
|
|
},
|
|
)
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn without_front(&self) -> List<T> {
|
|
List {
|
|
head: self.head.as_ref().map(|node| node.parent.clone()).flatten(),
|
|
}
|
|
}
|
|
|
|
pub fn get_data(&self) -> Option<&T> {
|
|
self.head.as_ref().map(|rc_node| &rc_node.data)
|
|
}
|
|
|
|
pub fn is_empty(&self) -> bool {
|
|
self.head.is_none()
|
|
}
|
|
|
|
pub fn ptr_eq(&self, other: &List<T>) -> bool {
|
|
match (self.head.as_ref(), other.head.as_ref()) {
|
|
(None, None) => true,
|
|
(None, Some(_)) | (Some(_), None) => false,
|
|
(Some(me), Some(them)) => Rc::ptr_eq(me, them),
|
|
}
|
|
}
|
|
}
|