import
java.util.*;
class
GFG{
static
class
Node
{
int
data;
Node next;
};
static
Node tail;
static
Node rotateHelper(Node blockHead,
Node blockTail,
int
d,
int
k)
{
if
(d ==
0
)
return
blockHead;
if
(d >
0
)
{
Node temp = blockHead;
for
(
int
i =
1
; temp.next.next!=
null
&&
i < k -
1
; i++)
temp = temp.next;
blockTail.next = blockHead;
tail = temp;
return
rotateHelper(blockTail, temp,
d -
1
, k);
}
if
(d <
0
)
{
blockTail.next = blockHead;
tail = blockHead;
return
rotateHelper(blockHead.next,
blockHead, d +
1
, k);
}
return
blockHead;
}
static
Node rotateByBlocks(Node head,
int
k,
int
d)
{
if
(head ==
null
|| head.next ==
null
)
return
head;
if
(d ==
0
)
return
head;
Node temp = head;
tail =
null
;
int
i;
for
(i =
1
; temp.next !=
null
&&
i < k; i++)
temp = temp.next;
Node nextBlock = temp.next;
if
(i < k)
head = rotateHelper(head, temp,
d % k, i);
else
head = rotateHelper(head, temp,
d % k, k);
tail.next = rotateByBlocks(nextBlock,
k, d % k);
return
head;
}
static
Node push(Node head_ref,
int
new_data)
{
Node new_node =
new
Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return
head_ref;
}
static
void
printList(Node node)
{
while
(node !=
null
)
{
System.out.print(node.data +
" "
);
node = node.next;
}
}
public
static
void
main(String[] args)
{
Node head =
null
;
for
(
int
i =
9
; i >
0
; i -=
1
)
head = push(head, i);
System.out.print(
"Given linked list "
);
printList(head);
int
k =
3
, d =
2
;
head = rotateByBlocks(head, k, d);
System.out.print(
"Rotated by blocks Linked list "
);
printList(head);
}
}