Skip to main content
Back to problems
#24
Medium Algorithms

Swap nodes in pairs

Linked List Recursion
69.0% acceptance
Jan 12, 2026
13072
511
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.)

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn swap_pairs(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    match head {
      None => None,
      Some(mut first) => {
        match first.next.take() {
          None => Some(first),
          Some(mut second) => {
            first.next = Self::swap_pairs(second.next.take());
            second.next = Some(first);
            Some(second)
          }
        }
      }
    }
  }
}