Member-only story
Reverse Linked List II
2 min readNov 1, 2021
Could you do it in one pass?
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.
Example 1:
Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]
Example 2:
Input: head = [5], left = 1, right = 1
Output: [5]
Constraints:
- The number of nodes in the list is
n
. 1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
dummyHead = ListNode(0, next = head)
#head = [1,2,3,4,5], left = 2, right = 4
start = dummyHead
cur = start.next
#find the node right before "left"
for _ in range(left - 1):
start = start.next
cur = start.next
#start = the node right before "left"#rever the needed
prev = None
for _ in range(right - left + 1):
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
# 4 > 3 > 2 > None
#end = the node after "right"
end = cur#start.next = 2
start.next.next = end
# 4 > 3 > 2 > 5
#cur = 4
#connect start with 4
start.next = prev
# 1 > 4 > 3 > 2 > 5
return dummyHead.next