Created
April 10, 2021 07:18
-
-
Save DonghyungKo/7506c639c7d0470b68b510f3114ae658 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
impl<T> LinkedList<T> { | |
/// Pop element from the back of LinkedList, or return `None` if empty | |
#[inline] | |
pub fn pop_back(&mut self) -> Option<T> { | |
self.pop_back_node().map(Node::into_element) | |
} | |
/// Pop node from the back of LinkedList, or return `None` if empty | |
/// This will unlink the last node from LinkedList | |
#[inline] | |
fn pop_back_node(&mut self) -> Option<Box<Node<T>>> { | |
self.tail.map(|node_ptr| { | |
unsafe { | |
if self.length > 1 { | |
self.tail = self.get_ith_node(self.head, self.length - 2); | |
} else { | |
self.tail = None; | |
} | |
match self.tail { | |
None => self.head = None, | |
Some(mut tail) => { | |
tail.as_mut().next = None; | |
} | |
} | |
} | |
self.length -= 1; | |
let node = unsafe { Box::from_raw(node_ptr.as_ptr()) }; | |
node | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment