1
macro_rules! next_node_as_ref {
2
($a: expr) => {
3
$a.as_ref().unwrap().next
4
};
5
}
6
macro_rules! next_node_as_mut {
7
($a: expr) => {
8
$a.as_mut().unwrap().next
9
};
10
}
11
impl Solution {
12
pub fn swap_pairs(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
13
if head.is_none() {
14
return None;
15
}
16
let mut cur_node = &mut head;
17

18
// while we have something to work with (.next has something)
19
while cur_node.is_some() && next_node_as_ref!(cur_node).is_some() {
20
// .take() Takes the value out of the option, leaving a None in its place.
21
let mut even_node = next_node_as_mut!(cur_node).take();
22

23
// taking next odd node's value
24
let next_odd_node = next_node_as_mut!(even_node).take();
25
// cur_node's .next points to next odd node
26
next_node_as_mut!(cur_node) = next_odd_node;
27
// even node's .next points to cur_node
28
next_node_as_mut!(even_node) = cur_node.take();
29
// switching cur_node with even node
30
cur_node.replace(even_node.unwrap());
31
// point cursor to .next.next
32
cur_node = &mut next_node_as_mut!(next_node_as_mut!(cur_node));
33
}
34
head
35
}
36
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0