Skip to content

Commit

Permalink
ds: Add IterMut in linked list
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Dec 14, 2023
1 parent de74a39 commit 7eb37a4
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions data_structures/src/list/single_v1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ pub struct Iter<'a, T> {
next: Option<&'a ListNode<T>>,
}

pub struct IterMut<'a, T> {
next: Option<&'a mut ListNode<T>>,
}

impl<T> ListNode<T> {
#[must_use]
pub fn new(value: T) -> Box<Self> {
Expand Down Expand Up @@ -114,6 +118,13 @@ impl<T> LinkedListV1<T> {
next: self.head.as_deref(),
}
}

#[must_use]
pub fn iter_mut(&mut self) -> IterMut<T> {
IterMut {
next: self.head.as_deref_mut(),
}
}
}

impl<T> Drop for LinkedListV1<T> {
Expand Down Expand Up @@ -184,6 +195,17 @@ impl<'a, T> Iterator for Iter<'a, T> {
}
}

impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut T;

fn next(&mut self) -> Option<Self::Item> {
self.next.take().map(|node| {
self.next = node.next.as_deref_mut();
&mut node.value
})
}
}

#[cfg(test)]
mod tests {
use super::LinkedListV1;
Expand Down Expand Up @@ -273,4 +295,20 @@ mod tests {
assert_eq!(val, num);
}
}

#[test]
fn test_iter_mut() {
let mut list = LinkedListV1::new();
list.push(2);
list.push(3);
list.push(5);
list.push(7);
for val in list.iter_mut() {
*val *= 2;
}
let nums = &[14, 10, 6, 4];
for (val, num) in list.iter().zip(nums) {
assert_eq!(val, num);
}
}
}

0 comments on commit 7eb37a4

Please sign in to comment.