From 987380ca9327a5e097d1b0a7661586eeb2f088d2 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sat, 1 Oct 2022 14:32:22 +0800 Subject: [PATCH 1/2] =?UTF-8?q?update=200024.=E4=B8=A4=E4=B8=A4=E4=BA=A4?= =?UTF-8?q?=E6=8D=A2=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=9A=84=E8=8A=82=E7=82=B9?= =?UTF-8?q?=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0024.两两交换链表中的节点.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index 10337a7f..3b86ac6f 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -380,5 +380,30 @@ function swapPairs($head) } ``` +Rust: + +```rust +// 虚拟头节点 +impl Solution { + pub fn swap_pairs(head: Option>) -> Option> { + 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 + } +} +``` + -----------------------
From 00ad23f45815ca3a371b6beae65da209433708cf Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sat, 1 Oct 2022 15:23:53 +0800 Subject: [PATCH 2/2] =?UTF-8?q?Update=200024.=E4=B8=A4=E4=B8=A4=E4=BA=A4?= =?UTF-8?q?=E6=8D=A2=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=9A=84=E8=8A=82=E7=82=B9?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0024.两两交换链表中的节点.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index 3b86ac6f..d65d0bca 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -405,5 +405,26 @@ impl Solution { } ``` +```rust +// 递归 +impl Solution { + pub fn swap_pairs(head: Option>) -> Option> { + 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) + } + } +} +``` + -----------------------