Chaturmind
LearnDSASystem DesignBlogPremium
Sign inGet started
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML

Company

  • Blog
  • Premium
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.

DSA›Linked Lists›Reverse Linked List II
MediumLinked Lists

Reverse Linked List II

linked-listin-place

Problem

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 (1-indexed), and return the reversed list.

Examples

Example 1

Input: head = [1,2,3,4,5], left = 2, right = 4

Output: [1,4,3,2,5]

Explanation: Nodes at positions 2 through 4 (values 2,3,4) are reversed in place; positions 1 and 5 stay put.

Example 2

Input: head = [5], left = 1, right = 1

Output: [5]

Explanation: Reversing a single node is a no-op.

Constraints

  • •The number of nodes in the list is n
  • •1 <= n <= 500
  • •-500 <= Node.val <= 500
  • •1 <= left <= right <= n

Hints

Hint 1

This is the same three-pointer (prev/curr/next) reversal as the full-list version — the difference is entirely about where you start and stop, and reconnecting the reversed sub-range back to the untouched parts.

Hint 2

Use a dummy node before head so 'left == 1' (reversing from the very start) isn't a special case needing separate logic.

Hint 3

Walk to the node just before position 'left' first — everything before that node never moves, and you need a stable reference to reconnect to it afterward.

Solutions

public ListNode reverseBetween(ListNode head, int left, int right) {
    ListNode dummy = new ListNode(0, head); // handles left == 1 without a special case
    ListNode beforeLeft = dummy;
    for (int i = 0; i < left - 1; i++) beforeLeft = beforeLeft.next; // walk to just before 'left'

    ListNode curr = beforeLeft.next; // this will become the TAIL of the reversed section
    ListNode prev = null;
    for (int i = 0; i < right - left + 1; i++) {
        ListNode next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }

    // Reconnect: beforeLeft -> (reversed section, head = prev) ... (reversed section, tail) -> curr (first node after the range)
    beforeLeft.next.next = curr; // the original 'left' node is now the tail of the reversed section
    beforeLeft.next = prev;      // prev is the new head of the reversed section
    return dummy.next;
}
Java

Time: O(n) · Space: O(1)