C++ Program For Reversing A Linked List In Groups Of Given Size – Set 2
Last Updated :
28 Nov, 2022
Given a linked list, write a function to reverse every k nodes (where k is an input to the function).
Examples:
Input: 1->2->3->4->5->6->7->8->NULL and k = 3
Output: 3->2->1->6->5->4->8->7->NULL.
Input: 1->2->3->4->5->6->7->8->NULL and k = 5
Output: 5->4->3->2->1->8->7->6->NULL.
We have already discussed its solution in below post
Reverse a Linked List in groups of given size | Set 1
In this post, we have used a stack which will store the nodes of the given linked list. Firstly, push the k elements of the linked list in the stack. Now pop elements one by one and keep track of the previously popped node. Point the next pointer of prev node to top element of stack. Repeat this process, until NULL is reached.
This algorithm uses O(k) extra space.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* next;
};
struct Node* Reverse( struct Node* head,
int k)
{
stack<Node*> mystack;
struct Node* current = head;
struct Node* prev = NULL;
while (current != NULL)
{
int count = 0;
while (current != NULL &&
count < k)
{
mystack.push(current);
current = current->next;
count++;
}
while (mystack.size() > 0)
{
if (prev == NULL)
{
prev = mystack.top();
head = prev;
mystack.pop();
}
else
{
prev->next = mystack.top();
prev = prev->next;
mystack.pop();
}
}
}
prev->next = NULL;
return head;
}
void push( struct Node** head_ref,
int new_data)
{
struct Node* new_node =
( struct Node*) malloc ( sizeof ( struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList( struct Node* node)
{
while (node != NULL)
{
printf ( "%d " , node->data);
node = node->next;
}
}
int main( void )
{
struct Node* head = NULL;
push(&head, 9);
push(&head, 8);
push(&head, 7);
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
printf ( "Given linked list " );
printList(head);
head = Reverse(head, 3);
printf ( "Reversed Linked list " );
printList(head);
return 0;
}
|
Output:
Given Linked List
1 2 3 4 5 6 7 8 9
Reversed list
3 2 1 6 5 4 9 8 7
Time complexity: O(n*k) where n is size of given linked list
Auxiliary Space: O(1)
Please refer complete article on Reverse a Linked List in groups of given size | Set 2 for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...