添加 0203.移除链表元素 0344.反转字符串 0376.摆动序列 0541.反转字符串II 剑指Offer05.替换空格 Rust版本
添加 0203.移除链表元素 0344.反转字符串 0376.摆动序列 0541.反转字符串II 剑指Offer05.替换空格 Rust版本
This commit is contained in:
@@ -487,17 +487,19 @@ RUST:
|
||||
// }
|
||||
impl Solution {
|
||||
pub fn remove_elements(head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
|
||||
let mut head = head;
|
||||
let mut dummy_head = ListNode::new(0);
|
||||
let mut cur = &mut dummy_head;
|
||||
while let Some(mut node) = head {
|
||||
head = std::mem::replace(&mut node.next, None);
|
||||
if node.val != val {
|
||||
cur.next = Some(node);
|
||||
let mut dummyHead = Box::new(ListNode::new(0));
|
||||
dummyHead.next = head;
|
||||
let mut cur = dummyHead.as_mut();
|
||||
// 使用take()替换std::men::replace(&mut node.next, None)达到相同的效果,并且更普遍易读
|
||||
while let Some(nxt) = cur.next.take() {
|
||||
if nxt.val == val {
|
||||
cur.next = nxt.next;
|
||||
} else {
|
||||
cur.next = Some(nxt);
|
||||
cur = cur.next.as_mut().unwrap();
|
||||
}
|
||||
}
|
||||
dummy_head.next
|
||||
dummyHead.next
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user