# Given a list, rotate the list to the right by k places, where k is non-negative.
#
# Example:
#
# Given 1->2->3->4->5->NULL and k = 2,
#
# return 4->5->1->2->3->NULL.

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head:
            return head

        p1 = head
        length = 0
        while p1:
            p1 = p1.next
            length += 1

        k = k % length

        p1 = head
        while k > 0:
            p1 = p1.next
            k -= 1

        if p1:
            new_head = head
            while p1.next:
                p1 = p1.next
                new_head = new_head.next

            p1.next = head
            head = new_head.next
            new_head.next = None

        return head

# Note:
# k can be greater than length of the list so we find length of the list and modulus k with it and then run simple algo
