# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
Time Complexity : O(n)
Space Complexity: O(1)
"""
# corner cases
if not head or not head.next:
return head
ptr = head
size = 0
# to find the size of list
while ptr:
size += 1
ptr = ptr.next
# to find the rotation required after k % size
rot = 0
if k % size == 0:
return head
else:
rot = k % size
k = rot
prev = head
curr = head.next
tmp_head = None
i = 0
flag = False
# now make the (size - k + 1)th node as a tmp_head node and (size -k + 2)th node's next point to null
# and then traverse upto the last node of list and connect the last node.next to the original head
# at last make the tmp_head as permanent head and return the head
while True:
i += 1
if i == (size - k):
prev.next = None
tmp_head = curr
flag = True
elif flag:
if not curr.next:
curr.next = head
head = tmp_head
break
else:
curr = curr.next
else:
prev = curr
curr = curr.next
return head