Skip to content

Commit 1dbf1a0

Browse files
Fix bounds on delete_ith (#880)
1 parent a45a382 commit 1dbf1a0

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

src/data_structures/linked_list.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,15 +144,15 @@ impl<T> LinkedList<T> {
144144
}
145145

146146
pub fn delete_ith(&mut self, index: u32) -> Option<T> {
147-
if self.length < index {
147+
if self.length <= index {
148148
panic!("Index out of bounds");
149149
}
150150

151151
if index == 0 || self.head.is_none() {
152152
return self.delete_head();
153153
}
154154

155-
if self.length == index {
155+
if self.length - 1 == index {
156156
return self.delete_tail();
157157
}
158158

@@ -499,4 +499,14 @@ mod tests {
499499
assert!(retrived_item.is_some());
500500
assert_eq!("B", *retrived_item.unwrap());
501501
}
502+
503+
#[test]
504+
#[should_panic(expected = "Index out of bounds")]
505+
fn delete_ith_panics_if_index_equals_length() {
506+
let mut list = LinkedList::<i32>::new();
507+
list.insert_at_tail(1);
508+
list.insert_at_tail(2);
509+
// length is 2, so index 2 is out of bounds
510+
list.delete_ith(2);
511+
}
502512
}

0 commit comments

Comments
 (0)