# Reverse Linked List II in C++

Suppose we have a linked list. We have to reverse the nodes from position m to n. We have to do it in one pass. So if the list is [1,2,3,4,5] and m = 2 and n = 4, then the result will be [1,4,,3,2,5]

Let us see the steps −

• There will be two methods, the reverseN() and reverseBetween(). The reverseBetween() will work as main method.
• define one link node pointer called successor as null
• The reverseN will work as follows −
• if n = 1, then successor := next of head, and return head
• last = reverseN(next of head, n - 1)
• the reverseBetween() method will be like −
• if m = 1, then return reverseN(head, n)
• next of head := reverseBetween(next of head, m – 1, n – 1)

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
for(int i = 1; i<v.size(); i++){
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
}
cout << "[";
while(ptr){
cout << ptr->val << ", ";
ptr = ptr->next;
}
cout << "]" << endl;
}
class Solution {
public:
ListNode* successor = NULL;
ListNode* reverseN(ListNode* head, int n ){
if(n == 1){
}
ListNode* last = reverseN(head->next, n - 1);
return last;
}
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(m == 1){
}
}
};
main(){
Solution ob;
vector<int> v = {1,2,3,4,5,6,7,8};
}
[1,2,3,4,5,6,7,8]
6
[1, 6, 5, 4, 3, 2, 7, 8, ]