添加 0203.移除链表元素 0344.反转字符串 0376.摆动序列 0541.反转字符串II 剑指Offer05.替换空格 Rust版本

添加 0203.移除链表元素 0344.反转字符串 0376.摆动序列 0541.反转字符串II 剑指Offer05.替换空格 Rust版本
This commit is contained in:
BaoTaoqi
2022-07-11 14:50:03 +08:00
parent e2d16c5894
commit c265c9220c
5 changed files with 111 additions and 8 deletions

View File

@@ -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
}
}
```