Reverse A Sublist Of Linked List

Introduction

The linked list is one of the most important concepts to know while preparing for interviews. Having a good grasp on linked list can be a huge plus point in coding interviews.

Problem Statement

Given a linked list and two integers (say ‘m’ and ‘n’). We need to reverse the list from position m to n and leave the rest of the list as it is.

Problem Statement Understanding

Let’s try to understand this problem with the help of examples.

If the list given to us is:

  • According to the problem statement, we need to reverse the given list from position m=3 to position n=5, i.e., from 3rd node to 5th node (both inclusive).
  • The sublist from position 3 to position 5 is 1→7→4, so we need to reverse this sublist of the given linked list.
  • Our final output linked list after reversing the sublist is:

Let’s take another example, let the input be 9→4→8→7→1→NULL, m = 2, n = 3.

  • So in this case, after reversing the sublist from position 2 to 3 (both inclusive), our final output list will be 9→8→4→7→1→NULL.
Some more examples

Sample Input 1: 1→3→5→7→9→11→13→NULL, m = 2, n = 4
Sample Output 1: 1→7→5→3→9→11→13→NULL

Sample Output 2: 1→2→5→6→4→8→NULL, m = 2, n = 6
Sample Output 2: 1→8→4→6→5→2→NULL

Now, I think from the above examples, the problem statement is clear. Let’s see how we can approach it.

Before moving to the approach section, try to think about how you can approach this problem.
If stuck, no problem, we will thoroughly see how we can approach this problem in the next section.

Let’s move to the approach section.

Approach

Our approach will be quite straightforward.

  • At first, we need to find the mth node.
  • Then we find the nth node.
  • After that, we need to detach the list that is present after the nth node and save the (n+1)th node’s address in a variable.
  • Then we need to reverse the sublist starting from the mth node to the nth node.
  • Now, we need to attach this reversed list after (m-1)th node and also attach the remaining list whose address we stored in a temporary variable after the nth node.

Following these steps will give us the required answer.

Algorithm

  • Initialize four pointers named StartRev, BeforeRev, EndRev, AfterRev with NULL and an integer variable i with 1.
  • Initialize a curr variable with the head pointer for iteration of the list.
  • Now, run a while loop till curr reaches NULL, and i is less than n.
  • Inside the while loop:
    • If i is less than m, update BeforeRev with curr.
    • If i is equal to m, update StartRev with curr.
    • If i is equal to n, update EndRev with curr and AfterRev with curr->next.
    • Increment i by 1.
  • Make EndRev->next as NULL to detach the list after the mth node.
  • Now, reverse the list with StartRev as starting node.
  • Check if BeforeRev is NULL or not:
    • If it is not NULL, then assign BeforeRev->next to EndRev.
    • Else update head with EndRev.
  • Assign StartRev->next with AfterRev.
  • Return the head pointer.

If you are not aware of how to reverse a linked list, please check this article Reversing a linked list.

Dry Run

Code Implementation:

#include 
using namespace std;

/* Node structure of a singly linked list */
class Node {
    public:
    int data;
    Node* next;
    Node(int x){
        data = x;
        next = NULL;
}
};

/* Using this function we will be printing the linked list */
void printingList(Node* head)
{
    Node* curr = head;
    while (curr != NULL) {
        cout << curr->data << " -> ";
        curr = curr->next;
    }
    cout<<"NULL";
    cout<next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}
 
/* Using this function we will be reversing the sublist from mth till nth position */
Node* ReverseFromMToN(Node* head, int m, int n)
{
    if (m == n)
        return head;

    Node* StartRev = NULL, *BeforeRev = NULL;
    Node* EndRev = NULL, *AfterRev = NULL;
 
    int i = 1;
    Node* curr = head;
    while (curr && i <= n) {
        if (i < m)
            BeforeRev = curr;
 
        if (i == m)
            StartRev = curr;
 
        if (i == n) {
            EndRev = curr;
            AfterRev = curr->next;
        }
 
        curr = curr->next;
        i++;
    }
    
    EndRev->next = NULL;
 
    EndRev = reverseList(StartRev);
 
    if (BeforeRev)
        BeforeRev->next = EndRev;

    else
        head = EndRev;
    
    StartRev->next = AfterRev;
 
    return head;
}

int main()
{
    Node *head = new Node(2);
    head->next = new Node(9);
    head->next->next = new Node(1);
    head->next->next->next = new Node(7);
    head->next->next->next->next = new Node(4);
    head->next->next->next->next->next = new Node(8);
    head->next->next->next->next->next->next = new Node(3);
    cout<<"Original given linked list before reversing sublist:"<

						 

Output

Original given linked list before reversing sublist:
2 -> 9 -> 1 -> 7 -> 4 -> 8 -> 3 -> NULL
Linked list after reversing sublist:
2 -> 9 -> 4 -> 7 -> 1 -> 8 -> 3 -> NULL

Time Complexity: O(n), n is the number of nodes present in the list

So, in this blog, we have tried to explain how you can reverse the sublist of a linked list in the most optimal way. This is a basic problem and is good for strengthening your concepts in LinkedList and if you want to practice more such problems, you can checkout Prepbytes (Linked List).

Previous post Search an element in a Doubly Linked List
Next post Remove duplicates from an unsorted linked list

Leave a Reply

Your email address will not be published. Required fields are marked *