# Rotate linked list clockwise by k nodes in swift

Swift program for Rotate linked list clockwise by k nodes. Here mentioned other language solution.

``````import Foundation
/*
Swift 4 program for
Rotate a list by moving each element
k times to the right.
Or clockwise rotation of linked list
*/
{
var data: Int;
init(_ data: Int)
{
self.data = data;
self.next = nil;
}
}
class SingleLL
{
init()
{
self.tail = nil;
}
{
{
}
else
{
// Append the node at last position
self.tail!.next = node;
}
self.tail = node;
}
func display()
{
{
return;
}
while (temp  != nil)
{
print("",temp!.data, terminator: " →");
// Visit to next node
temp = temp!.next;
}
print(" NULL");
}
// This are perform the linked list rotation
func rotation(_ k: Int)
{
// Define some auxiliary variable
var count: Int = 0;
// Count number of node in linked list
while (auxiliary  != nil)
{
// 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
self.tail = auxiliary;
// Set that there is no node after of tail
self.tail!.next = nil;
}
// Handles the request to perform rotation
// k is indicate node rotation
func clockwiseRotation(_ k: Int)
{
if (k <= 0)
{
// When invalid given k
return;
}
{
return;
}
print(" Before rotate ");
self.display();
print(" Given k :",k);
// Perform rotation
self.rotation(k);
print(" After rotate ");
self.display();
print("\n");
}
static func main()
{
let sll1: SingleLL = SingleLL();
let 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);
}
}
SingleLL.main();``````

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