class
Node:
def
__init__(
self
, data):
self
.data
=
data
self
.
next
=
None
def
rotateHelper(blockHead, blockTail,
d, tail, k):
if
(d
=
=
0
):
return
blockHead, tail
if
(d >
0
):
temp
=
blockHead
i
=
1
while
(temp.
next
.
next
!
=
None
and
i < k
-
1
):
temp
=
temp.
next
i
+
=
1
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)
def
rotateByBlocks(head, k, d):
if
(head
=
=
None
or
head.
next
=
=
None
):
return
head
if
(d
=
=
0
):
return
head
temp
=
head
tail
=
None
i
=
1
while
temp.
next
!
=
None
and
i < k:
temp
=
temp.
next
i
+
=
1
nextBlock
=
temp.
next
if
(i < k):
head, tail
=
rotateHelper(head, temp,
d
%
k, tail, i)
else
:
head, tail
=
rotateHelper(head, temp,
d
%
k, tail, k)
tail.
next
=
rotateByBlocks(nextBlock,
k, d
%
k);
return
head;
def
push(head_ref, new_data):
new_node
=
Node(new_data)
new_node.data
=
new_data
new_node.
next
=
(head_ref)
(head_ref)
=
new_node
return
head_ref
def
printList(node):
while
(node !
=
None
):
print
(node.data, end
=
' '
)
node
=
node.
next
if
__name__
=
=
'__main__'
:
head
=
None
for
i
in
range
(
9
,
0
,
-
1
):
head
=
push(head, i)
print
(
"Given linked list "
)
printList(head)
k
=
3
d
=
2
head
=
rotateByBlocks(head, k, d)
print
(
"Rotated by blocks Linked list "
)
printList(head)