diff --git a/src/data_structures/linked_list.rs b/src/data_structures/linked_list.rs index 208a14376ae..5f782d82967 100644 --- a/src/data_structures/linked_list.rs +++ b/src/data_structures/linked_list.rs @@ -144,7 +144,7 @@ impl LinkedList { } pub fn delete_ith(&mut self, index: u32) -> Option { - if self.length < index { + if self.length <= index { panic!("Index out of bounds"); } @@ -152,7 +152,7 @@ impl LinkedList { return self.delete_head(); } - if self.length == index { + if self.length - 1 == index { return self.delete_tail(); } @@ -499,4 +499,14 @@ mod tests { assert!(retrived_item.is_some()); assert_eq!("B", *retrived_item.unwrap()); } + + #[test] + #[should_panic(expected = "Index out of bounds")] + fn delete_ith_panics_if_index_equals_length() { + let mut list = LinkedList::::new(); + list.insert_at_tail(1); + list.insert_at_tail(2); + // length is 2, so index 2 is out of bounds + list.delete_ith(2); + } }