My Python Solution


  • 0
    Y

    Inspired by Remove Nth Node From End of List - Simple Java solution in one pass using two pointers(fast and slow).

    class Solution(object):
        def rotateRight(self, head, k):
            """
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            """
            
            if not head:
                return []
            
            #get length of the linked list
            lenlist = 0
            tmp = head
            while tmp:
                lenlist+=1
                tmp=tmp.next
    
            k = k%lenlist
            
            if k>=lenlist or k==0:
                return head
            
            # rotation
            fast = slow = head
            for _ in range(k):
                fast = fast.next
            while fast.next:
                fast = fast.next
                slow = slow.next
            oldhead = head
            newhead = slow.next
            slow.next = None
            fast.next = oldhead
            return newhead
    

Log in to reply
 

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