/**
 * struct ListNode {
 *    int val;
 *    struct ListNode *next;
 * };
 */

class Solution {
public:
  ListNode* rotateRight(ListNode* head, int k) {
    // corner case
    if (!head || !head->next || k <= 0) return head;

    int len = 1;
    auto tail = head;
    while (tail->next) {
      ++len;
      tail = tail->next;
    }

    k %= len;
    if (!k) return head;

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

    auto new_head = p->next;
    p->next = nullptr;
    tail->next = head;

    return new_head;
  }
};