# Rotate linked list clockwise by k nodes in golang

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

``````package main
import "fmt"
/*
Go program for
Rotate a list by moving each element
k times to the right.
Or clockwise rotation of linked list
*/
data int
}
data,
nil,
}
}
type SingleLL struct {
}
func getSingleLL() * SingleLL {
// return new SingleLL
return &SingleLL {
nil,
nil,
}
}
} else {
// Append the node at last position
this.tail.next = node
}
this.tail = node
}
func(this SingleLL) display() {
return
}
for (temp != nil) {
fmt.Print(" ", temp.data, " →")
// Visit to next node
temp = temp.next
}
fmt.Println(" NULL")
}
// This are perform the linked list rotation
func(this *SingleLL) rotation(k int) {
// Define some auxiliary variable
var count int = 0
// Count number of node in linked list
for (auxiliary != nil) {
// visit to next node
auxiliary = auxiliary.next
count++
}
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
for (count > 1) {
// Visit to next node
auxiliary = auxiliary.next
count--
}
// 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 = nil
}
// Handles the request to perform rotation
// k is indicate node rotation
func(this SingleLL) clockwiseRotation(k int) {
if k <= 0 {
// When invalid given k
return
}
return
}
fmt.Println(" Before rotate ")
this.display()
fmt.Println(" Given k : ", k)
// Perform rotation
this.rotation(k)
fmt.Println(" After rotate ")
this.display()
fmt.Println("\n")
}
func main() {
var sll1 * SingleLL = getSingleLL()
var sll2 * SingleLL = getSingleLL()
// 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