My clean Python code


  • 0
    C
    # 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 head == None or head.next == None:
                return head
            else:
                length = 0
                count = head
                while(count!=None):
                    length += 1
                    count = count.next
                k = k % length
                if k > 0:
                    fast = head
                    slow = head
                
                    while(k >= 1):
                        fast = fast.next
                        k -= 1
                    while(fast.next):
                        fast = fast.next
                        slow = slow.next
                
                    temp = slow.next
                    slow.next = None
                    fast.next = head
                    return temp
                else:
                    return head

Log in to reply
 

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