# Rotate a linked list by k nodes in python

Python program for Rotate a linked list by k nodes. Here problem description and other solutions.

``````#  Python 3 program for

def __init__(self, data) :
self.data = data
self.next = None

class SingleLL :
def __init__(self) :
self.tail = None

def insert(self, value) :
#  Create a new node
else :
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")

def validKNode(self, k) :
count = 0
#  Count node
while (temp != None) :
count += 1
if (count > k) :
#  When K is correct
return k

#  Visit to next node
temp = temp.next

#  Need to change k value
return k % count

def rotate(self, k) :
if (k <= 0) :
return

return

#  Assume that k is less the number of nodes
#  Otherwise first count number of nodes
#  Then use modulo operator and change k = k % count
#  Here implement
k = self.validKNode(k)
if (k == 0) :
#  because after rotate get same result
return
else :
#  Use to find the location of rotate node
counter = 1
point = None
#  Find last node in rotation
while (temp != None and temp.next != None) :
if (counter == k) :
point = temp

counter += 1
temp = temp.next

#  When roated node are exist
if (point != None) :
#  Modified node position
#  Modified tail
self.tail = point
point.next = None

def main() :
sll = SingleLL()
k = 3
#  1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL
sll.insert(1)
sll.insert(2)
sll.insert(3)
sll.insert(4)
sll.insert(5)
sll.insert(6)
sll.insert(7)
sll.insert(8)
print("Before Rotate ", k ," Nodes")
sll.display()
#  Rotate node
sll.rotate(k)
print("After Rotate ", k ," Nodes")
sll.display()

if __name__ == "__main__": main()``````

Output

``````Before Rotate  3  Nodes
1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL
After Rotate  3  Nodes
4 → 5 → 6 → 7 → 8 → 1 → 2 → 3 → NULL``````

## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.