-
Notifications
You must be signed in to change notification settings - Fork 10
/
swap_nodes_in_pairs.rs
46 lines (41 loc) · 1.4 KB
/
swap_nodes_in_pairs.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
use super::ListNode;
struct Solution;
/* Python版方便理解记忆
def swap_pairs(self, head):
if head and head.next:
right = head.next
head.next = self.swap_pairs(right.next)
right.next = head
return right
# 5->None这种情况就不换
return head
*/
impl Solution {
fn swap_pairs_best(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
// TODO 用map unwrap Option<T>,学到了,如果是head是None则不会走map的函数
head.map(|mut left| match left.next.take() {
None => left,
Some(mut right) => {
left.next = Self::swap_pairs(right.next.take());
right.next = Some(left);
right
}
})
}
fn swap_pairs(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
Self::recursive(head)
}
fn recursive(mut node: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
if node.is_some() && node.as_ref()?.next.is_some() {
// right是一对节点中靠右节点(奇数下标的节点),node是靠左的
let mut right = node.as_mut()?.next.take();
// 下一对的第一个
let next_pair = right.as_mut()?.next.take();
node.as_mut()?.next = Self::recursive(next_pair);
right.as_mut()?.next = node;
right
} else {
node
}
}
}