Skip to content

Instantly share code, notes, and snippets.

@DonghyungKo
Created April 10, 2021 03:38
Show Gist options
  • Save DonghyungKo/6729fb6392056e12791f178b0433510f to your computer and use it in GitHub Desktop.
Save DonghyungKo/6729fb6392056e12791f178b0433510f to your computer and use it in GitHub Desktop.
// setter methods (by index)
impl<T> LinkedList<T> {
/// Insert node to i-th index of LinkedList.
/// If given index if bigger than length of LinkedList,
/// Node will be attached to the tail of LinkedList
#[inline]
pub fn insert(&mut self, val: T, index: u32) {
self.insert_node(Box::new(Node::new(val)), index)
}
#[inline]
fn insert_node(&mut self, mut node: Box<Node<T>>, index: u32) {
if index > self.length {
return self.push_back_node(node);
}
if index == 0 {
return self.push_front_node(node);
}
unsafe {
let mut front = self.get_ith_node(self.head, index - 1).unwrap(); // None is unreachable
let back = front.as_ref().next;
// [front] -> [middle] -> [back]
node.next = back;
let middle = NonNull::new_unchecked(Box::into_raw(node));
front.as_mut().next = Some(middle);
}
self.length += 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment