题解:
1.首先确定k的取值,可能超过链表长度,所有对 k%=n 来确定
2.需要找到k前面的结点和最右位置的结点,可以使用双指针得到。
/**
* 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) return nullptr;
int n = 0;
for( auto p = head ; p ; p = p->next) n++;
k %= n ;
auto first = head , second = head;
while(k--) first = first->next;
while(first->next)
{
first = first->next;
second = second->next;
}
first->next = head;
head = second->next;
second->next = nullptr;
return head;
}
};