
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
- next of (next of head) = head, and next of head := successor, return last
- 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
#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){ ListNode *head = new ListNode(v[0]); for(int i = 1; i<v.size(); i++){ ListNode *ptr = head; while(ptr->next != NULL){ ptr = ptr->next; } ptr->next = new ListNode(v[i]); } return head; } void print_list(ListNode *head){ ListNode *ptr = head; 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){ successor = head->next; return head; } ListNode* last = reverseN(head->next, n - 1); head->next->next = head; head->next = successor; return last; } ListNode* reverseBetween(ListNode* head, int m, int n) { if(m == 1){ return reverseN(head, n); } head->next = reverseBetween(head->next, m - 1, n - 1); return head; } }; main(){ Solution ob; vector<int> v = {1,2,3,4,5,6,7,8}; ListNode *head = make_list(v); print_list(ob.reverseBetween(head, 2, 6)); }
Input
[1,2,3,4,5,6,7,8] 2 6
Output
[1, 6, 5, 4, 3, 2, 7, 8, ]
Advertisements