@@ -78,14 +78,18 @@ impl Solution {
7878 pub fn remove_elements (head : Option <Box <ListNode >>, val : i32 ) -> Option <Box <ListNode >> {
7979 let mut dummyHead = Box :: new (ListNode :: new (0 ));
8080 dummyHead. next = head ;
81- let mut cur = dummyHead. as_mut ();
81+ let mut cur : & mut ListNode = dummyHead. as_mut ();
8282 // 使用take()替换std::men::replace(&mut node.next, None)达到相同的效果,并且更普遍易读
8383 while let Some (nxt ) = cur . next. take () {
8484 if nxt . val == val {
8585 cur . next = nxt . next;
8686 } else {
8787 cur . next = Some (nxt );
88- cur = cur . next. as_mut (). unwrap ();
88+ cur = cur . next. as_mut (). unwrap (); // coercion
89+ // ^ Option<Box<ListNode>>
90+ // ^ Option<&mut Box<ListNode>>
91+ // ^ &mut Box<ListNode>
92+ // deref coerce -> & mut ListNode
8993 }
9094 }
9195 dummyHead. next
@@ -94,3 +98,41 @@ impl Solution {
9498```
9599
96100向这位老哥学习,使用take,管它用不用,先取下来再说。并且 先把option刨了
101+
102+
103+ ``` rust
104+
105+ # struct Solution {}
106+ #
107+ # // Definition for singly-linked list.
108+ # #[derive(PartialEq , Eq , Clone , Debug )]
109+ # pub struct ListNode {
110+ # pub val : i32 ,
111+ # pub next : Option <Box <ListNode >>
112+ # }
113+ #
114+ # impl ListNode {
115+ # #[inline]
116+ # fn new (val : i32 ) -> Self {
117+ # ListNode {
118+ # next : None ,
119+ # val
120+ # }
121+ # }
122+ # }
123+
124+ impl Solution {
125+ pub fn remove_elements (mut head : Option <Box <ListNode >>, val : i32 ) -> Option <Box <ListNode >> {
126+ let mut res : Option <Box <ListNode >> = None ;
127+ let mut ptr : & mut Option <Box <ListNode >> = & mut res ;
128+ while let Some (mut x ) = head {
129+ head = x . next. take ();
130+ if x . val != val {
131+ * ptr = Some (x );
132+ ptr = & mut ptr . as_mut (). unwrap (). next;
133+ }
134+ }
135+ res
136+ }
137+ }
138+ ```
0 commit comments