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

  • next of (next of head) = head, and next of head := successor, return last

  • if m = 1, then return reverseN(head, n)

  • next of head := reverseBetween(next of head, m - 1, n - 1)

Example

Let us see the following implementation to get better understanding −

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;
   }
};

Input

[1,2,3,4,5,6,7,8]
2
6

Output

[1,6,5,4,3,2,7,8]
raja
Published on 03-Feb-2020 10:30:08
Advertisements