Easy to understand python O(n)


  • 0
    L
    def rotateRight(self, head, k):
        if not head:
            return
        if k == 0:
            return head
        length = 0
        current = head
        while current:
            length += 1
            #current will point at the last node of initial list
            if current.next is None:
                break
            current = current.next
    
        k %= length
        if k == 0:
            return head
        
        current.next = head
        for i in xrange(length - k):
            #current will point at the last node of desired list 
            current = current.next
    
        head = current.next
        current.next = None
        return head

Log in to reply
 

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