Open In App

Reverse a doubly linked list in groups of K size

Last Updated : 07 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given a Doubly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end should be considered as a group and must be reversed.

Examples: 

Input: 1 <-> 2 <-> 3 <-> 4 <-> 5 <-> 6 <-> NULL, k = 2
Output: 2 <-> 1 <-> 4 <-> 3 <-> 6 <-> 5 <-> NULL.
Explanation : Linked List is reversed in a group of size k = 2.

Reverse-a-doubly-linked-list-in-groups-of-K-size-2


Input: 1 <-> 2 <-> 3 <-> 4 <-> 5 <-> 6 <-> NULL, k = 4
Output: 4 <-> 3 <-> 2 <-> 1 <-> 6 -> 5 -> NULL.
Explanation : Linked List is reversed in a group of size k = 4.

Reverse-a-doubly-linked-list-in-groups-of-K-size-4

[Expected Approach – 1] Using Recursion – O(n) Time and O(n) Space:

The idea is to reverse the first k nodes of the list and update the head of the list to the new head of this reversed segment. Then, connect the tail of this reversed segment to the result of recursively reversing the remaining portion of the list.

Follow the steps below to solve the problem:

  • If the list is empty, return the head.
  • Reverse the first k nodes using the reverseKNodes() function and update the new Head with the reversed list head.
  • Connect the tail of the reversed group to the result of recursively reversing the remaining list using the reverseKGroup() function.
  • Update next and prev pointers during the reversal.
  • At last, return the new Head of the reversed list from the first group.
C++
// C++ code to reverse a doubly linked 
// list in groups of K size

#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node *next;
    Node *prev;

    Node(int x) {
        data = x;
        next = nullptr;
        prev = nullptr;
    }
};

// Helper function to reverse K nodes
Node *reverseKNodes(Node *head, int k) {
    Node *curr = head, *prev = nullptr, *next = nullptr;
    int count = 0;

    while (curr != nullptr && count < k) {
        next = curr->next;
        curr->next = prev;
        curr->prev = nullptr;
        if (prev != nullptr) {
            prev->prev = curr;
        }
        prev = curr;
        curr = next;
        count++;
    }

    return prev;
}

// Recursive function to reverse in groups of K
Node *reverseKGroup(Node *head, int k) {
    if (head == nullptr) {
        return head;
    }
    Node *groupHead = nullptr;
    Node *newHead = nullptr;

    // Move temp to the next group
    Node *temp = head;
    int count = 0;
    while (temp && count < k) {
        temp = temp->next;
        count++;
    }

    // Reverse the first K nodes
    groupHead = reverseKNodes(head, k);

    // Connect the reversed group with the next part
    if (newHead == nullptr) {
        newHead = groupHead;
    }

    // Recursion for the next group
    head->next = reverseKGroup(temp, k);
    if (head->next != nullptr) {
        head->next->prev = head;
    }

    return newHead;
}

void printList(Node *head) {
    Node *curr = head;
    while (curr != nullptr) {
        cout << curr->data << " ";
        curr = curr->next;
    }
    cout << endl;
}

int main() {
  
    // Creating a sample doubly linked list:
    // 1 <-> 2 <-> 3 <-> 4 <-> 5 <-> 6
    Node *head = new Node(1);
    head->next = new Node(2);
    head->next->prev = head;
    head->next->next = new Node(3);
    head->next->next->prev = head->next;
    head->next->next->next = new Node(4);
    head->next->next->next->prev = head->next->next;
    head->next->next->next->next = new Node(5);
    head->next->next->next->next->prev = head->next->next->next;
    head->next->next->next->next->next = new Node(6);
    head->next->next->next->next->next->prev = head->next->next->next->next;

    head = reverseKGroup(head, 2);
    printList(head);

    return 0;
}
C Java Python C# JavaScript

Output
2 1 4 3 6 5 

Time complexity: O(n), where n is the number of nodes in linked list.
Auxiliary Space: O(n)

[Expected Approach – 2] Using Iterative Method – O(n) Time and O(1) Space:

The idea is to traverse the list in groups of k nodes, reversing each group. After reversing a group, link it to the previous group by updating the tail pointer. Continue until the entire list is traversed and return the new head.

Follow the steps below to solve the problem:

  • Initialize pointers curr to traverse the list, newHead to track the new head of the list, tail to connect the previous group to the current group.
  • For each group of k nodes:
    • Set groupHead to the current node.
    • Then, reverse the group of k nodes by updating next and prev pointers.
    • Also, keep track of the prev node (which will be the new head of the reversed group) and the next node (which is the start of the next group).
  • Connect the end of the previous group to the start of the current reversed group.
  • Repeat the process for the remaining nodes in the list until all nodes are traversed.

Below is the implementation of the above approach: 

C++
// C++ code to reverse a doubly linked 
// list in groups of K size

#include <iostream>
using namespace std;

class Node {
  public:
    int data;
    Node *next;
    Node *prev;

    Node(int x) {
        data = x;
        next = nullptr;
        prev = nullptr;
    }
};

// Helper function to reverse K nodes iteratively
Node *reverseKGroup(Node *head, int k) {
    if (head == nullptr) {
        return head;
    }

    Node *curr = head;
    Node *newHead = nullptr;
    Node *tail = nullptr;

    while (curr != nullptr) {
        Node *groupHead = curr;
        Node *prev = nullptr;
        Node *next = nullptr;
        int count = 0;

        // Reverse the nodes in the current group
        while (curr != nullptr && count < k) {
            next = curr->next;
            curr->next = prev;
            curr->prev = nullptr;
            if (prev != nullptr) {
                prev->prev = curr;
            }
            prev = curr;
            curr = next;
            count++;
        }

        // If newHead is null, set it to the
          // last node of the first group
        if (newHead == nullptr) {
            newHead = prev;
        }

        // Connect the previous group to the 
          // current reversed group
        if (tail != nullptr) {
            tail->next = prev;
            prev->prev = tail;
        }

        // Move tail to the end of the reversed group
        tail = groupHead;
    }

    return newHead;
}

void printList(Node *head) {
    Node *curr = head;
    while (curr != nullptr) {
        cout << curr->data << " ";
        curr = curr->next;
    }
    cout << endl;
}

int main() {
    
    // Creating a sample doubly linked list:
    // 1 <-> 2 <-> 3 <-> 4 <-> 5 <-> 6
    Node *head = new Node(1);
    head->next = new Node(2);
    head->next->prev = head;
    head->next->next = new Node(3);
    head->next->next->prev = head->next;
    head->next->next->next = new Node(4);
    head->next->next->next->prev = head->next->next;
    head->next->next->next->next = new Node(5);
    head->next->next->next->next->prev = head->next->next->next;
    head->next->next->next->next->next = new Node(6);
    head->next->next->next->next->next->prev = head->next->next->next->next;

    head = reverseKGroup(head, 2);
    printList(head);

    return 0;
}
C Java Python C# JavaScript

Output
2 1 4 3 6 5 

Time complexity: O(n), where n is the number of nodes in linked list.
Auxiliary Space: O(1)



Similar Reads

three90RightbarBannerImg