07. Reverse Linked List II
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
Check if left
is equal to right
. If they are equal, there is no need to reverse the list, so return the original head
.
Initialize two pointers:
prev
as NULL
(to keep track of the node before the left
-th node in the sublist).
curr
as head
(to traverse the list).
Traverse the list to position left - 1
using a for
loop:
Start the loop with i
initialized to 1.
In each iteration, update prev
to curr
and move curr
to the next node in the list (curr = curr->next
).
After the loop, prev
points to the node before the left
-th node, and curr
points to the left
-th node to be reversed.
Create two additional pointers:
first
as prev
(to keep track of the node before the reversed sublist).
newend
as curr
(to keep track of the first node in the reversed sublist).
nextNode
as curr->next
(to initialize the next node after the reversed sublist).
Use a for
loop to reverse the sublist from left
to right
:
Initialize a loop variable i
to 0.
In each iteration, reverse the curr
node by updating curr->next
to point to prev
, then update prev
to curr
, and curr
to nextNode
.
Additionally, update nextNode
to the next node in the list (nextNode = nextNode->next
) if nextNode
is not NULL
.
After the loop, the sublist from left
to right
is reversed, and prev
points to the new head of this reversed sublist, while curr
points to the node after the reversed sublist.
Check if first
is not NULL
(i.e., the sublist to be reversed does not start at the beginning of the list). If not NULL
, update first->next
to point to the new head of the reversed sublist (prev
).
If first
is NULL
, it means the sublist to be reversed starts at the beginning of the list. In this case, update head
to point to the new head of the reversed sublist (prev
).
Time Complexity: O(n)
Auxiliary Space Complexity: O(1)
For discussions, questions, or doubts related to this solution, please visit our . 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 repository.