Merge pull request #1675 from Jack-Zhang-1314/patch-6

update 0024.两两交换链表中的节点 about rust
This commit is contained in:
程序员Carl
2022-10-08 09:47:51 +08:00
committed by GitHub

View File

@ -380,5 +380,51 @@ function swapPairs($head)
}
```
Rust:
```rust
// 虚拟头节点
impl Solution {
pub fn swap_pairs(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut dummy_head = Box::new(ListNode::new(0));
dummy_head.next = head;
let mut cur = dummy_head.as_mut();
while let Some(mut node) = cur.next.take() {
if let Some(mut next) = node.next.take() {
node.next = next.next.take();
next.next = Some(node);
cur.next = Some(next);
cur = cur.next.as_mut().unwrap().next.as_mut().unwrap();
} else {
cur.next = Some(node);
cur = cur.next.as_mut().unwrap();
}
}
dummy_head.next
}
}
```
```rust
// 递归
impl Solution {
pub fn swap_pairs(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
if head == None || head.as_ref().unwrap().next == None {
return head;
}
let mut node = head.unwrap();
if let Some(mut next) = node.next.take() {
node.next = Solution::swap_pairs(next.next);
next.next = Some(node);
Some(next)
} else {
Some(node)
}
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>