@@ -78,14 +78,18 @@ impl Solution {
78
78
pub fn remove_elements (head : Option <Box <ListNode >>, val : i32 ) -> Option <Box <ListNode >> {
79
79
let mut dummyHead = Box :: new (ListNode :: new (0 ));
80
80
dummyHead. next = head ;
81
- let mut cur = dummyHead. as_mut ();
81
+ let mut cur : & mut ListNode = dummyHead. as_mut ();
82
82
// 使用take()替换std::men::replace(&mut node.next, None)达到相同的效果,并且更普遍易读
83
83
while let Some (nxt ) = cur . next. take () {
84
84
if nxt . val == val {
85
85
cur . next = nxt . next;
86
86
} else {
87
87
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
89
93
}
90
94
}
91
95
dummyHead. next
@@ -94,3 +98,41 @@ impl Solution {
94
98
```
95
99
96
100
向这位老哥学习,使用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