Reverse a doubly linked list in groups of given size | Set 2
Given a doubly-linked list containing n nodes. The problem is to reverse every group of k nodes in the list.
Input: List: 10<->8<->4<->2, K=2
Input: List: 1<->2<->3<->4<->5<->6<->7<->8, K=3
Recursive Approach: The recursive approach to solving this problem is discussed in Set-1 of this article. Here, we are discussing the iterative approach.
Iterative Approach: This approach is a mix of two algorithms – reversing a doubly-linked list and reversing a linked list in a group of a given size. The function reverseK() individually reverses every k size linked list and connects them using prevFirst pointer that keeps track of the node that is bound to come after reversing. Follow the steps below to solve this problem:
- If N is less than equal to 1, then return head.
- Initialize the variables prevFirst as nullptr and curr as head.
- Initialize the variable firstPass as true.
- Traverse over a while loop till curr is not equal to null and perform the following tasks:
- Initialize the variable count as 0.
- Initialize the variables first as curr, next and prev as null.
- Traverse over a while loop till curr is not equal to null and count is less than K and perform the following tasks:
- Set the value of next as curr->next.
- If count equals 0 then set curr->next as null else curr->next as curr->prev.
- Set curr->prev as next, prev as curr and curr as next.
- Increase the value of count by 1.
- If firstPass is true then set head as next->prev and firstPass as false.
- Else, set prevFirst->next as prev.
- Set prevFirst as first.
- After performing the above steps, print the value of head as the answer.
Below is the implementation of the above approach.
7 1 6 8 9 4
Time Complexity: O(N)
Auxiliary Space: O(1)
Please Login to comment...