Problem Statement

Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.

Example 1:

Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]

Example 2:

Input: head = [5], left = 1, right = 1
Output: [5]

Constraints:

Problem Link

Reverse Linked List II - LeetCode

Code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        
        if(!head)
            return NULL;
        
        ListNode *temp = head,*lprev = NULL,*l = NULL,*r = NULL;
        
        
        
        while(left--)//positioning *l pointer and *lprev whihch points to the previous node of *l
        {
            lprev = l;
            l = temp;
            temp = temp->next;
            
        }
        
        temp = head;
        
        while(right--)//positioning *r pointer 
        {
            r = temp;
            temp = temp->next;
            
        }
        
        ListNode *rnext = r->next;//*rnext whihch points to the next node of *r
        
        
        //Reversing the list from *l to *r
        ListNode *prev = rnext, *curr = l, *currn;
        
        while(curr!=rnext)
        {
            currn = curr->next;
            curr->next = prev;
            prev = curr;
            curr = currn;
            
        }
        
        if(lprev)
            lprev->next = prev;
        else//if the list is reversed from the beginning
            head = prev;
        
        return head;
        
        
    }
};