07. Reverse Linked List II
The problem can be found at the following link: Question Link
My Approach
Check if
leftis equal toright. If they are equal, there is no need to reverse the list, so return the originalhead.Initialize two pointers:
prevasNULL(to keep track of the node before theleft-th node in the sublist).currashead(to traverse the list).
Traverse the list to position
left - 1using aforloop:Start the loop with
iinitialized to 1.In each iteration, update
prevtocurrand movecurrto the next node in the list (curr = curr->next).
After the loop,
prevpoints to the node before theleft-th node, andcurrpoints to theleft-th node to be reversed.Create two additional pointers:
firstasprev(to keep track of the node before the reversed sublist).newendascurr(to keep track of the first node in the reversed sublist).nextNodeascurr->next(to initialize the next node after the reversed sublist).
Use a
forloop to reverse the sublist fromlefttoright:Initialize a loop variable
ito 0.In each iteration, reverse the
currnode by updatingcurr->nextto point toprev, then updateprevtocurr, andcurrtonextNode.Additionally, update
nextNodeto the next node in the list (nextNode = nextNode->next) ifnextNodeis notNULL.
After the loop, the sublist from
lefttorightis reversed, andprevpoints to the new head of this reversed sublist, whilecurrpoints to the node after the reversed sublist.Check if
firstis notNULL(i.e., the sublist to be reversed does not start at the beginning of the list). If notNULL, updatefirst->nextto point to the new head of the reversed sublist (prev).If
firstisNULL, it means the sublist to be reversed starts at the beginning of the list. In this case, updateheadto 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++)
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
if(left == right) return head;
ListNode* prev = NULL;
ListNode* curr = head;
for(int i=1;i<left;i++) {
prev = curr;
curr = curr -> next;
}
ListNode* first = prev;
ListNode* newend = curr;
ListNode* nextNode = curr -> next;
for(int i = 0;i<right - left + 1;i++) {
curr -> next = prev;
prev = curr;
curr = nextNode;
if(nextNode != NULL) nextNode = nextNode -> next;
}
if(first != NULL) first -> next = prev;
else head = prev;
newend -> next = curr;
return head;
}
};
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
Was this helpful?