class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution():
def rotateRight(self, head, k):
if not head:
return None
cur, n = head, 1
while cur.next:
cur, n = cur.next, n+1
cur.next = head
tail = cur = head
for _ in range(n - k % n):
tail, cur = cur, cur.next
tail.next = None
return cur
if __name__ == "__main__":
head, head.next, head.next.next, head.next.next.next, head.next.next.next.next \
= ListNode(1), ListNode(2), ListNode(3), ListNode(4), ListNode(5)
print(Solution().rotateRight(head, 2))