思路:先将链表首尾相连,成为一个环装列表,然后找到新的头,断开列表,将NULL赋给列表的末尾即可。
/**
* 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) {
if(!head) return NULL;
ListNode *cur=head;
int n=1;
while(cur->next)
{
cur=cur->next;
++n;
}
cur->next=head;
int m=n-k%n;
while(m--)
{
cur=cur->next;
}
ListNode* ans=cur->next;
cur->next=NULL;
return ans;
}
};