Hello,
I am trying to implement a Single LinkedList, in an effort to better understand Options and Box<> ptrs.
- Would appreciate on my two approach to adding to Head -
add_head1
andadd_head2
. - Having some trouble implementing add_tail(). Would appreciate some help understanding the error.
type NodePointer = Option<Box<Node>>;
#[derive(Debug)]
struct LinkedList {
head: NodePointer,
}
#[derive(Debug)]
struct Node {
element: u32,
next: NodePointer,
}
impl LinkedList {
fn new() -> LinkedList {
LinkedList { head: None, }
}
fn add_head1(&mut self, element: u32) {
let prev_head = self.head.take();
let new_head = Some(Box::new(Node {
element,
next: prev_head,
}));
self.head = new_head;
}
fn add_head2(&mut self, element: u32) {
let mut new_head = Box::new(Node {
element,
next: None,
});
if self.head.is_some() {
new_head.next.insert(self.head.take().unwrap());
}
self.head.insert(new_head);
}
fn remove_head(&mut self) -> Option<u32> {
match self.head.take() {
Some(previous_head) => {
self.head = previous_head.next;
Some(previous_head.element)
}
None => None,
}
}
fn add_tail(&mut self, element: u32) {
let new_node = Some(Box::new( Node {
element,
next: None,
}));
if self.head.is_none() {
self.head = new_node;
} else {
// traverse the list till end, then insert.
let mut runner_node = &self.head;
while (*runner_node).as_ref().unwrap().next.is_some() {
runner_node = &runner_node.as_ref().unwrap().next;
}
// Tried both the following, getting different compile error for all of them.
(*runner_node).as_ref().unwrap().next = *new_node;
// (*runner_node).as_ref().unwrap().next = new_node;
// runner_node.as_ref().unwrap().next = new_node;
}
}