Categories
Tags
311 words
2 minutes
Leetcode92:Reverse Linked List II
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:
- Create a dummy node
dummy
to simplify edge cases (like reversing from the head). - Move
pre
to the node right before positionleft
. - Set
curr = pre.next
to point to the start of the sublist to be reversed. - Perform
right - left
head insertions, where each node aftercurr
is inserted right afterpre
.
π 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 afterpre
, 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/