Very simple 6ms C++ solution with least iterations possible


  • 0
    N
        ListNode* rotateRight(ListNode* head, int k) {
            if (k == 0 || head == NULL || head->next == NULL) return head;
            ListNode *last = head->next;
            ListNode *newhead;
            int count = 0;
            
            //Count number of nodes in the list
            for (count = 2; last->next != NULL; last = last->next) 
                count++;
            
            //Check if no need to rotate
            if((k %= count) == 0)
                return head;
            
            //Make it circular    
            last->next = head;
            
            //Find the new head
            last = head;
            for (int i = 0; i < count-k-1; i++) 
                last = last->next;
    
            newhead = last->next;
            last->next = NULL;
    
            return newhead;
        }
    

Log in to reply
 

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