07. Reverse Linked List II
The problem can be found at the following link: Question Link
My Approach
Check if
left
is equal toright
. If they are equal, there is no need to reverse the list, so return the originalhead
.Initialize two pointers:
prev
asNULL
(to keep track of the node before theleft
-th node in the sublist).curr
ashead
(to traverse the list).
Traverse the list to position
left - 1
using afor
loop:Start the loop with
i
initialized to 1.In each iteration, update
prev
tocurr
and movecurr
to the next node in the list (curr = curr->next
).
After the loop,
prev
points to the node before theleft
-th node, andcurr
points to theleft
-th node to be reversed.Create two additional pointers:
first
asprev
(to keep track of the node before the reversed sublist).newend
ascurr
(to keep track of the first node in the reversed sublist).nextNode
ascurr->next
(to initialize the next node after the reversed sublist).
Use a
for
loop to reverse the sublist fromleft
toright
:Initialize a loop variable
i
to 0.In each iteration, reverse the
curr
node by updatingcurr->next
to point toprev
, then updateprev
tocurr
, andcurr
tonextNode
.Additionally, update
nextNode
to the next node in the list (nextNode = nextNode->next
) ifnextNode
is notNULL
.
After the loop, the sublist from
left
toright
is reversed, andprev
points to the new head of this reversed sublist, whilecurr
points to the node after the reversed sublist.Check if
first
is notNULL
(i.e., the sublist to be reversed does not start at the beginning of the list). If notNULL
, updatefirst->next
to point to the new head of the reversed sublist (prev
).If
first
isNULL
, it means the sublist to be reversed starts at the beginning of the list. In this case, updatehead
to point to the new head of the reversed sublist (prev
).
Time and Auxiliary Space Complexity
Time Complexity:
O(n)
Auxiliary Space Complexity:
O(1)
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the rishabhv12/Daily-Leetcode-Solution repository.
Last updated