/** * 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) { ListNode* tail = NULL; int len = getLen(head, tail); if (len <= 0) return head; k %= len; if (k == 0) return head; k = len - k; ListNode* cur = head; while (k-->1) cur = cur->next; ListNode* newHead = cur->next; tail->next = head; cur->next = NULL; return newHead; } int getLen(ListNode* head, ListNode*& tail) { int cnt = 0; while (head != NULL) { cnt ++; tail = head; head = head->next; } return cnt; } };