Python solution (commented for every step)


  • 0
    N
    class Solution(object):
        def rotateRight(self, head, k):
            """
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            """
            ref = head
            length = 0
    
            # Find length
            while head:
                head = head.next
                length += 1
    
            # For a list with length 3, rotating k times(k = 0, 3, 6, 9) won't 
            # change the list
            if length < 2 or k % length == 0:
                return ref
    
            # Find k elements before length
            prev = None
            current = ref
    
            # Calculate k % length because rotating a list l + k times
            # is just like rotating it k times
            for _ in xrange(length - (k % length)):
                prev, current = current, current.next
    
    
            # Prevent cycling by deleting the next link of last element
            prev.next = None
            new_head = current
    
            # This is when we rotate length * k times
            if not current: 
                return ref
    
            # Progress until the end of the list and connect the end to the head
            while current.next:
                current = current.next
            current.next = ref
    
            # return the rest of the list
            return new_head
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.