Skip to main content
Back to problems
#1721
Medium Algorithms

Swapping nodes in a linked list

Linked List Two Pointers
69.2% acceptance
Feb 25, 2026
5715
211
You are given the head of a linked list, and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn swap_nodes(head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> {
    // Collect values into a vec, swap, rebuild
    let mut vals = Vec::new();
    let mut cur = &head;
    while let Some(node) = cur {
      vals.push(node.val);
      cur = &node.next;
    }
    let n = vals.len();
    let k = k as usize;
    vals.swap(k - 1, n - k);
    // Rebuild list
    let mut head: Option<Box<ListNode>> = None;
    for &v in vals.iter().rev() {
      let mut node = ListNode::new(v);
      node.next = head;
      head = Some(Box::new(node));
    }
    head
  }
}