LC 61. Rotate List

Nilanjan Deb · April 5, 2020

This is my CPP solution.

class Solution {
private:
    void rotate(vector<int>& nums, int k) {
        int t[100200],n=nums.size();
        k = k%n;
        for(int i=0;i<n;i++){
            if(i>=n-k){
                t[i+k-n] = nums[i];
            }
            else{
                t[i+k] = nums[i];
            }
        }
        nums.clear();
        for(int i=0;i<n;i++){
            nums.push_back(t[i]);
        }
    }
public:
    ListNode* rotateRight(ListNode* head, int k) {
        vector<int> store;
        ListNode* temp = head;
        if(!head)
            return head;
        while(temp){
            store.push_back(temp->val);
            temp = temp->next;
        }
        rotate(store,k);
        temp = head;
        int i = 0;
        while(temp){
            temp->val = store[i];
            i++;
            temp = temp->next;
        }
        return head;
    }
};


Dicussion Forum