#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* rotateHelper(struct Node* blockHead,
struct Node* blockTail,
int d, struct Node** tail,
int k)
{
if (d == 0)
return blockHead;
if (d > 0) {
struct Node* temp = blockHead;
for (int i = 1; temp->next->next &&
i < k - 1; i++)
temp = temp->next;
blockTail->next = blockHead;
*tail = temp;
return rotateHelper(blockTail, temp,
d - 1, tail, k);
}
if (d < 0) {
blockTail->next = blockHead;
*tail = blockHead;
return rotateHelper(blockHead->next,
blockHead, d + 1, tail, k);
}
}
struct Node* rotateByBlocks(struct Node* head,
int k, int d)
{
if (!head || !head->next)
return head;
if (d == 0)
return head;
struct Node* temp = head, *tail = NULL;
int i;
for (i = 1; temp->next && i < k; i++)
temp = temp->next;
struct Node* nextBlock = temp->next;
if (i < k)
head = rotateHelper(head, temp, d % k,
&tail;, i);
else
head = rotateHelper(head, temp, d % k,
&tail;, k);
tail->next = rotateByBlocks(nextBlock, k,
d % k);
return head;
}
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = new 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()
{
struct Node* head = NULL;
for (int i = 9; i > 0; i -= 1)
push(&head;, i);
printf("Given linked list \n");
printList(head);
int k = 3, d = 2;
head = rotateByBlocks(head, k, d);
printf("\nRotated by blocks Linked list \n");
printList(head);
return (0);
}