My easy to understand java and python solution with minor explanation


  • 0
    T

    Java:

    public ListNode rotateRight(ListNode head, int k) {

        if( head == null || head.next == null ){
            return head;
        }
        
        
        int start = 1;
        int end = 1;
        ListNode tempHead = head;
        ListNode startNode = head;
        ListNode endNode = head;
        while( endNode.next !=null ){
            end++;
            endNode = endNode.next;
        }
        // the expression of end-k%end is very important, this considers rotation
        while( start != end-k%end ){
            start++;
            startNode = startNode.next;
        }
    
        endNode.next = tempHead;
        head = startNode.next;
        startNode.next = null;
        
        return head;
        
    }
    

    python:

    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        
        if head == None or head.next == None:
            return head
        
        start = 1
        end = 1
        tempHead = head
        startNode = head
        endNode = head
        
        while endNode.next != None:
            end +=1
            endNode = endNode.next
        
        while start != end-k%end:
            start +=1
            startNode = startNode.next
        
        endNode.next = tempHead
        head = startNode.next
        startNode.next = None
        
        return head

Log in to reply
 

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