Skip to content

Instantly share code, notes, and snippets.

@DonghyungKo
Created April 10, 2021 03:11
Show Gist options
  • Save DonghyungKo/962bea13d78d3b42fd7e9c082fb5d55d to your computer and use it in GitHub Desktop.
Save DonghyungKo/962bea13d78d3b42fd7e9c082fb5d55d to your computer and use it in GitHub Desktop.
// setter methods
impl<T> LinkedList<T> {
/// Appends element to the back.
#[inline]
pub fn push_back(&mut self, val: T) {
self.push_back_node(Box::new(Node::new(val)))
}
/// Appends element to the front
#[inline]
pub fn push_front(&mut self, val: T) {
self.push_front_node(Box::new(Node::new(val)))
}
/// Appends the given node to the back of LinkedList
#[inline]
fn push_back_node(&mut self, node: Box<Node<T>>) {
unsafe {
let node = Some(NonNull::new_unchecked(Box::into_raw(node)));
match self.tail {
None => self.head = node,
Some(mut tail) => tail.as_mut().next = node,
}
self.tail = node;
self.length += 1;
}
}
/// Appends the given node to the front of LinkedList
#[inline]
fn push_front_node(&mut self, node: Box<Node<T>>) {
unsafe {
let mut node = Some(NonNull::new_unchecked(Box::into_raw(node)));
match self.head {
None => self.tail = node,
Some(head) => node.as_mut().unwrap().as_mut().next = Some(head),
}
self.head = node;
self.length += 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment