Merge pull request #1674 from Jack-Zhang-1314/patch-5

update 206翻转链表 about rust
This commit is contained in:
程序员Carl
2022-10-07 09:46:45 +08:00
committed by GitHub

View File

@ -588,5 +588,45 @@ object Solution {
} }
``` ```
Rust:
双指针法:
```rust
impl Solution {
pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut cur = head;
let mut pre = None;
while let Some(mut node) = cur.take() {
cur = node.next;
node.next = pre;
pre = Some(node);
}
pre
}
}
```
递归法:
```rust
impl Solution {
pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
fn rev(
mut head: Option<Box<ListNode>>,
mut pre: Option<Box<ListNode>>,
) -> Option<Box<ListNode>> {
if let Some(mut node) = head.take() {
let cur = node.next;
node.next = pre;
pre = Some(node);
return rev(cur, pre);
}
pre
}
rev(head, None)
}
}
```
----------------------- -----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div> <div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>