my python solution


  • 0
    G
    # 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 or k == 0:
                return head
            length, p = 0, head
            while p:
                length += 1
                p = p.next
            k = k % length
            if k == 0:
                return head
            fast, slow = head, head
            while k:
                fast = fast.next
                k -= 1
            
            while fast and fast.next:
                fast = fast.next
                slow = slow.next
            new_head = slow.next
            slow.next = None
            fast.next = head
            return new_head
    

Log in to reply
 

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