Skip to main content
Back to problems
#61
Medium Algorithms

Rotate list

Linked List Two Pointers
41.3% acceptance
Jan 12, 2026
11167
1545
Given the head of a linked list, rotate the list to the right by k places.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn rotate_right(head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> {
    if head.is_none() || k == 0 {
      return head;
    }
    
    // Calculate length and get to the last node
    let mut len = 1;
    let mut current = &head;
    while let Some(node) = current {
      if node.next.is_some() {
        current = &node.next;
        len += 1;
      } else {
        break;
      }
    }
    
    // Calculate effective rotation
    let k = k % len;
    if k == 0 {
      return head;
    }
    
    // Find the new tail (at position len - k - 1)
    let mut head = head;
    let steps = len - k - 1;
    let mut current = &mut head;
    
    for _ in 0..steps {
      if let Some(node) = current {
        current = &mut node.next;
      }
    }
    
    // Split the list
    let mut new_head = None;
    if let Some(node) = current {
      new_head = node.next.take();
    }
    
    // Connect the old tail to the old head
    let mut new_tail = &mut new_head;
    while let Some(node) = new_tail {
      if node.next.is_none() {
        node.next = head;
        break;
      }
      new_tail = &mut node.next;
    }
    
    new_head
  }
}