Reverse Linked List II (Reverse a Sub-list)
Problem
Thought Process
Solution
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
if (n==m):
return head
prev, curr = None, head
i = 0
# after skipping 'p-1' nodes, current will point to 'm'th node
while curr is not None and i < m-1:
prev = curr
curr = curr.next
i+=1
#node previous of mth node so we can connect it
previousNode = prev
mThNode = curr
i=0
#reversing the elements between p and q
while curr is not None and i < n-m+1:
nextN = curr.next
curr.next = prev
prev = curr
curr = nextN
i+=1
if previousNode is not None:
previousNode.next = prev
else: #this means p == 1 i.e., we are changing the first node (head) of the LinkedList
head = prev
mThNode.next = curr
return headLast updated