24. Swap Nodes in Pairs Medium

@problem@discussion
#Linked List#Recursion



1/**
2 * [24] Swap Nodes in Pairs
3 *
4 * Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
5 *  
6 * Example 1:
7 * <img alt="" src="https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg" style="width: 422px; height: 222px;" />
8 * Input: head = [1,2,3,4]
9 * Output: [2,1,4,3]
10 * 
11 * Example 2:
12 * 
13 * Input: head = []
14 * Output: []
15 * 
16 * Example 3:
17 * 
18 * Input: head = [1]
19 * Output: [1]
20 * 
21 *  
22 * Constraints:
23 * 
24 * The number of nodes in the list is in the range [0, 100].
25 * 0 <= Node.val <= 100
26 * 
27 */
28pub struct Solution {}
29#[allow(unused_imports)]
30use crate::util::linked_list::{ListNode, to_list};
31
32// problem: https://leetcode.com/problems/swap-nodes-in-pairs/
33// discuss: https://leetcode.com/problems/swap-nodes-in-pairs/discuss/?currentPage=1&orderBy=most_votes&query=
34
35// submission codes start here
36
37// Definition for singly-linked list.
38// #[derive(PartialEq, Eq, Clone, Debug)]
39// pub struct ListNode {
40//   pub val: i32,
41//   pub next: Option<Box<ListNode>>
42// }
43// 
44// impl ListNode {
45//   #[inline]
46//   fn new(val: i32) -> Self {
47//     ListNode {
48//       next: None,
49//       val
50//     }
51//   }
52// }
53impl Solution {
54    pub fn swap_pairs(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
55        let (mut i, n) = (0, 2);
56        let mut dummy = Some(Box::new(ListNode::new(-1)));
57        let mut refdummy = &mut dummy;
58        while let Some(mut node) = head {
59            head = node.next.take();
60            node.next = refdummy.as_mut().unwrap().next.take();
61            refdummy.as_mut().unwrap().next = Some(node);
62            i += 1;
63            if i == n {
64                while refdummy.as_ref().unwrap().next.is_some() {
65                    refdummy = &mut refdummy.as_mut().unwrap().next;
66                }
67                i = 0;
68            }
69        }
70
71        dummy.unwrap().next
72    }
73}
74
75// submission codes end
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    #[test]
82    fn test_24() {
83        let n = to_list(vec![1,2,3,4,5]);
84        let x = Solution::swap_pairs(n);
85        x.as_ref().unwrap().print();
86    }
87}
88


Back
© 2025 bowen.ge All Rights Reserved.