You are given the head of a singly linked list and two integers left and right where 1 <= left <= right <= n
(n is the length of the list). Reverse the nodes of the list from position left
to position right
, and return the reversed list.
Input:
Output:
left
.left
to right
.left
position.left
to right
positions.Here’s the implementation in Python:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseBetween(head: ListNode, left: int, right: int) -> ListNode:
if not head:
return None
# Position just before the start of the to-be-reversed section
dummy = ListNode(0)
dummy.next = head
prev = dummy
# Move prev to the node just before the `left` position
for _ in range(left - 1):
prev = prev.next
# Reverse from left to right
current = prev.next
reverse = None
for _ in range(right - left + 1):
next_node = current.next
current.next = reverse
reverse = current
current = next_node
# Connect reversed part with the previous part
prev.next.next = current
prev.next = reverse
return dummy.next
left
position and perform the reversal in a segment which takes linear time.This ensures an optimal and efficient approach for reversing a sublist within a singly linked list.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?