C++ 9ms


  • 0
    N
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* rotateRight(ListNode* head, int k) {
            if(head == NULL || head->next == NULL)
            {
                return head;
            }
            
            m_steps = k;
            m_length = 0;
            for(ListNode* tmp = head; tmp != NULL; tmp = tmp-> next, ++m_length) ;
            
            int i = 0;
            rotateRightR(head, head, head->next, i);
            
            return head;
        }
        
    private:
        void rotateRightR(ListNode* &head, ListNode* prev, ListNode* last, int& i)
        {
            if(last->next != NULL)
            {
                rotateRightR(head, last, last->next, i);
            }
            
            if(i < m_steps % m_length)
            {
                prev->next = NULL;
                last->next = head;
                head = last;
                ++i;
            }
        }
        
    private:
        int m_length;
        int m_steps;
    };```

Log in to reply
 

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