Reverse Linked List II (Reverse a Sub-list)
Problem
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Thought Process
The problem follows the In-place Reversal of a LinkedList pattern. We can use a similar approach as in Reverse a Linked List I. Here are the steps we need to follow:
Skip the first
p-1
nodes, to reach the node at positionp
.Remember the node at position
p-1
to be used later to connect with the reversed sub-list.Next, reverse the nodes from
p
toq
using the same approach discussed in Reverse a Linked List I.Connect the
p-1
andq+1
nodes to the reversed sub-list.
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 head
Last updated
Was this helpful?