# Rotate linked list clockwise by k nodes in python

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

``````#  Python 3 program for
#  Rotate a list by moving each element
#  k times to the right.
#  Or clockwise rotation of linked list

def __init__(self, data) :
self.data = data
self.next = None
class SingleLL :
def __init__(self) :
self.tail = None
else :
#  Append the node at last position
self.tail.next = node
self.tail = node
def display(self) :
return
while (temp != None) :
print("",temp.data, end =" →")
#  Visit to next node
temp = temp.next
print(" NULL")
#  This are perform the linked list rotation
def rotation(self, k) :
#  Define some auxiliary variable
count = 0
#  Count number of node in linked list
while (auxiliary != None) :
#  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 = None
#  Handles the request to perform rotation
#  k is indicate node rotation
def clockwiseRotation(self, k) :
if (k <= 0) :
#  When invalid given k
return
return
print(" Before rotate ")
self.display()
print(" Given k : " + str(k))
#  Perform rotation
self.rotation(k)
print(" After rotate ")
self.display()
print("\n")
def main() :
sll1 = SingleLL()
sll2 = 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)

if __name__=="__main__":
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