# Rotate linked list clockwise by k nodes in kotlin

Kotlin program for Rotate linked list clockwise by k nodes. Here more solutions.

``````/*
Kotlin program for
Rotate a list by moving each element
k times to the right.
Or clockwise rotation of linked list
*/
{
var data: Int;
constructor(data: Int)
{
this.data = data;
this.next = null;
}
}
class SingleLL
{
constructor()
{
this.tail = null;
}
{
{
}
else
{
// Append the node at last position
this.tail?.next = node;
}
this.tail = node;
}
fun display(): Unit
{
{
return;
}
while (temp != null)
{
print(" " + temp.data + " →");
// Visit to next node
temp = temp.next;
}
println(" NULL");
}
// This are perform the linked list rotation
fun rotation(k: Int): Unit
{
// Define some auxiliary variable
var count: Int = 0;
// Count number of node in linked list
while (auxiliary != null)
{
// visit to next node
auxiliary = auxiliary.next;
count += 1;
}
if (count <= 1)
{
// When have less than 2 nodes in linked list
return;
}
// Get actual rotation
count = k % count;
if (count == 0)
{
// When actual linked list are not affected
return;
}
// Find the rotational node
while (count > 1)
{
// Visit to next node
auxiliary = auxiliary?.next;
count -= 1;
}
// Connecting the last node to first node of linked list
// Set new last node
this.tail = auxiliary;
// Set that there is no node after of tail
this.tail?.next = null;
}
// Handles the request to perform rotation
// k is indicate node rotation
fun clockwiseRotation(k: Int): Unit
{
if (k <= 0)
{
// When invalid given k
return;
}
{
return;
}
println(" Before rotate ");
this.display();
println(" Given k : " + k);
// Perform rotation
this.rotation(k);
println(" After rotate ");
this.display();
println("\n");
}
}
fun main(args: Array < String > ): Unit
{
val sll1: SingleLL = SingleLL();
val sll2: SingleLL = SingleLL();
// 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL
// 4 → 9 → 7 → 3 → 8 → 6 → -2 → NULL
// Test case
sll1.clockwiseRotation(3);
sll2.clockwiseRotation(18);
}``````

Output

`````` Before rotate
1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL
Given k : 3
After rotate
4 → 5 → 6 → 7 → 8 → 1 → 2 → 3 → NULL

Before rotate
4 → 9 → 7 → 3 → 8 → 6 → -2 → NULL
Given k : 18
After rotate