-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path24-Swap_Nodes_in_Pairs.rs
More file actions
38 lines (38 loc) · 1.06 KB
/
Copy path24-Swap_Nodes_in_Pairs.rs
File metadata and controls
38 lines (38 loc) · 1.06 KB
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
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
pub fn swap_pairs(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
// Recursive approach: swap pairs by rearranging nodes
match head {
Some(mut node1) => {
match node1.next {
Some(mut node2) => {
// Swap: node2 becomes head, node1.next points to recursive result
node1.next = Self::swap_pairs(node2.next);
node2.next = Some(node1);
Some(node2)
}
None => {
// No pair to swap, return as is
Some(node1)
}
}
}
None => None,
}
}
}