Skip to content

Commit 27381c9

Browse files
Merge pull request youngyangyang04#1674 from Jack-Zhang-1314/patch-5
update 206翻转链表 about rust
2 parents fa2a8a7 + a8a9884 commit 27381c9

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

problems/0206.翻转链表.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -588,5 +588,45 @@ object Solution {
588588

589589
}
590590
```
591+
592+
Rust:
593+
双指针法:
594+
595+
```rust
596+
impl Solution {
597+
pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
598+
let mut cur = head;
599+
let mut pre = None;
600+
while let Some(mut node) = cur.take() {
601+
cur = node.next;
602+
node.next = pre;
603+
pre = Some(node);
604+
}
605+
pre
606+
}
607+
}
608+
```
609+
610+
递归法:
611+
612+
```rust
613+
impl Solution {
614+
pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
615+
fn rev(
616+
mut head: Option<Box<ListNode>>,
617+
mut pre: Option<Box<ListNode>>,
618+
) -> Option<Box<ListNode>> {
619+
if let Some(mut node) = head.take() {
620+
let cur = node.next;
621+
node.next = pre;
622+
pre = Some(node);
623+
return rev(cur, pre);
624+
}
625+
pre
626+
}
627+
rev(head, None)
628+
}
629+
}
630+
```
591631
-----------------------
592632
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
 (0)