Skip to content

Commit c797ce7

Browse files
committed
Add LinkedList::remove()
LinkedList::remove() removes the element at the specified index and returns it. Signed-off-by: Bijan Tabatabai <[email protected]>
1 parent ecde10f commit c797ce7

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/liballoc/collections/linked_list.rs

+46
Original file line numberDiff line numberDiff line change
@@ -878,6 +878,52 @@ impl<T> LinkedList<T> {
878878
unsafe { self.split_off_after_node(split_node, at) }
879879
}
880880

881+
/// Removes the element at the given index and returns it.
882+
///
883+
/// This operation should compute in O(n) time.
884+
///
885+
/// # Panics
886+
/// Panics if at >= len
887+
///
888+
/// # Examples
889+
///
890+
/// ```
891+
/// #![feature(linked_list_remove)]
892+
/// use std::collections::LinkedList;
893+
///
894+
/// let mut d = LinkedList::new();
895+
///
896+
/// d.push_front(1);
897+
/// d.push_front(2);
898+
/// d.push_front(3);
899+
///
900+
/// assert_eq!(d.remove(1), 2);
901+
/// assert_eq!(d.remove(0), 3);
902+
/// assert_eq!(d.remove(0), 1);
903+
/// ```
904+
#[unstable(feature = "linked_list_remove", issue = "69210")]
905+
pub fn remove(&mut self, at: usize) -> T {
906+
let len = self.len();
907+
assert!(at < len, "Cannot remove at an index outside of the list bounds");
908+
909+
// Below, we iterate towards the node at the given index, either from
910+
// the start or the end, depending on which would be faster.
911+
let offset_from_end = len - at - 1;
912+
if at <= offset_from_end {
913+
let mut cursor = self.cursor_front_mut();
914+
for _ in 0..at {
915+
cursor.move_next();
916+
}
917+
cursor.remove_current().unwrap()
918+
} else {
919+
let mut cursor = self.cursor_back_mut();
920+
for _ in 0..offset_from_end {
921+
cursor.move_prev();
922+
}
923+
cursor.remove_current().unwrap()
924+
}
925+
}
926+
881927
/// Creates an iterator which uses a closure to determine if an element should be removed.
882928
///
883929
/// If the closure returns true, then the element is removed and yielded.

0 commit comments

Comments
 (0)