Skip to main content
Back to problems
#92
Medium Algorithms

Reverse linked list ii

Linked List
51.0% acceptance
Jan 12, 2026
12867
780
Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn reverse_between(head: Option<Box<ListNode>>, left: i32, right: i32) -> Option<Box<ListNode>> {
    if left == right {
      return head;
    }
    
    // Convert list to vector
    let mut vals = Vec::new();
    let mut curr = &head;
    while let Some(node) = curr {
      vals.push(node.val);
      curr = &node.next;
    }
    
    // Reverse the subarray from left-1 to right-1 (0-indexed)
    let l = (left - 1) as usize;
    let r = (right - 1) as usize;
    vals[l..=r].reverse();
    
    // Convert back to linked list
    let mut dummy = Box::new(ListNode { val: 0, next: None });
    let mut curr = &mut dummy;
    
    for val in vals {
      curr.next = Some(Box::new(ListNode { val, next: None }));
      curr = curr.next.as_mut().unwrap();
    }
    
    dummy.next
  }
}