Share my python code, easy understand


  • 0
    class Solution(object):
    def getlength(self,head):
        if not head:return 0
        res=0
        while head:
            res+=1
            head=head.next
        return res
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        
        if not head:return head
        length=self.getlength(head)
        k=k%length  ###considering k is very large,more than the length of List 
        if k==0:return head
        p=ListNode(0)
        p.next=head
        q=p
        while p.next:
            if k>0:
                k-=1
            else:
                q=q.next
            p=p.next
        r=q.next  #place the right k nodes(start from r) in the front of the ListNode(head)
        q.next=None
        p.next=head
        return r

Log in to reply
 

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