<script>
class Node
{
constructor()
{
this
.data = 0;
this
.next =
null
;
}
}
var
tail;
function
rotateHelper(blockHead,
blockTail, d, k)
{
if
(d == 0)
return
blockHead;
if
(d > 0)
{
var
temp = blockHead;
for
(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;
}
function
rotateByBlocks(head, k, d)
{
if
(head ==
null
|| head.next ==
null
)
return
head;
if
(d == 0)
return
head;
var
temp = head;
tail =
null
;
var
i;
for
(i = 1; temp.next !=
null
&&
i < k; i++)
temp = temp.next;
var
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;
}
function
push(head_ref, new_data)
{
var
new_node =
new
Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return
head_ref;
}
function
printList(node)
{
while
(node !=
null
)
{
document.write(node.data +
" "
);
node = node.next;
}
}
var
head =
null
;
for
(i = 9; i > 0; i -= 1)
head = push(head, i);
document.write(
"Given linked list <br/>"
);
printList(head);
w
var
k = 3, d = 2;
head = rotateByBlocks(head, k, d);
document.write(
"<br/>Rotated by blocks Linked list <br/>"
);
printList(head);
</script>