less than 1 minute read

<-M 61> Rotate List

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(head == nullptr || k == 0)
            return head;

        int len = 1;
        ListNode *p = head;

        while(p->next) {
            len++;
            p = p->next;
        }

        k = len - k % len;

        p->next = head;
        for(int i = 0; i < k; i++)
            p = p->next;

        head = p->next;
        p->next = nullptr;

        return head;
    }
};