leetcode/
remove_elements.rs1use crate::ListNode;
17
18pub struct Solution;
19
20impl Solution {
21 pub fn remove_elements(head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
22 let mut dummy = Some(Box::new(ListNode{ next: head, val: 0 }));
23 let mut node = &mut dummy;
24 while node.is_some() && node.as_ref().unwrap().next.is_some() {
25 if node.as_ref().unwrap().next.as_ref().unwrap().val == val {
26 let n = node.as_mut().unwrap().next.take();
27 node.as_mut().unwrap().next = n.unwrap().next;
28 continue;
29 }
30 node = &mut node.as_mut().unwrap().next;
31 }
32 dummy.unwrap().next
33 }
34}
35
36#[cfg(test)]
37mod tests {
38 use super::*;
39 use crate::list;
40
41 #[test]
42 fn test() {
43 let cases = vec![
44 (vec![1,2,3,4,5], (list![1,2,6,3,4,5,6], 6)),
45 (vec![], (list![], 6)),
46 ];
47 let t = |v, t| ListNode::into_vec(Solution::remove_elements(v, t));
48 for (expect, (input, val)) in cases {
49 assert_eq!(expect, t(input, val));
50 }
51 }
52}