311 words
2 minutes
Leetcode92:Reverse Linked List II
2025-04-22

Leetcode 92: Reverse Linked List II#

🧠 Problem Description#

Given the head of a singly linked list and two integers left and right, reverse the nodes of the list from position left to position right, and return the reversed list.

  • Example Input:

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

    [1,4,3,2,5]

πŸ”§ Solution Idea: Head Insertion Method#

βœ… Steps:#

  1. Create a dummy node dummy to simplify edge cases (like reversing from the head).
  2. Move pre to the node right before position left.
  3. Set curr = pre.next to point to the start of the sublist to be reversed.
  4. Perform right - left head insertions, where each node after curr is inserted right after pre.

πŸ” Core Loop Explanation#

curr = pre.next
for _ in range(right - left):
    temp = curr.next         # β‘  Get the node after curr
    curr.next = temp.next    # β‘‘ Detach temp from its current position
    temp.next = pre.next     # β‘’ Point temp to the front of the reversed part
    pre.next = temp          # β‘£ Insert temp after pre

βœ… Example of Insertion:#

Initial list: 1 β†’ 2 β†’ 3 β†’ 4 β†’ 5, reverse positions 2~4
After operations: 1 β†’ 4 β†’ 3 β†’ 2 β†’ 5


πŸ“Œ Head Insertion Technique Summary#

The head insertion method is a common linked list technique especially useful for partial reversals. The core idea is:

β€œTake the next node after curr and insert it right after pre, repeatedly.”

🎯 Typical Use Cases:#

  • Reversing a sublist
  • Insertion sort on linked list

βœ… Full Python Code#

class Solution:
    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
        dummy = ListNode(0)
        dummy.next = head
        pre = dummy

        for _ in range(left - 1):
            pre = pre.next

        curr = pre.next
        for _ in range(right - left):
            temp = curr.next
            curr.next = temp.next
            temp.next = pre.next
            pre.next = temp

        return dummy.next

πŸ”š Summary#

This problem demonstrates the powerful β€œhead insertion” technique for in-place linked list reversal within a specified range. It is a classic and elegant approach to mastering linked list manipulation.

Leetcode92:Reverse Linked List II
https://nanshanvv.github.io/shuchangwen-webpage/posts/leetcode/92/
Author
Shuchang Wen
Published at
2025-04-22