给定一个链表,旋转链表,使得每个节点向右移动k个位置,其中k是一个非负数
样例
样例 1:
输入:1->2->3->4->5 k = 2
输出:4->5->1->2->3
样例 2:
输入:3->2->1 k = 1
输出:1->3->2
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: the List
* @param k: rotate to the right k places
* @return: the list after rotation
*/
ListNode * rotateRight(ListNode * head, int k) {
// write your code here
if(k==0||head==NULL) return head;
ListNode*p=head;
int len=0;
while(p)
{
len++;
p=p->next;
}
k=k%len;
if(k==0) return head;
p=head;
ListNode* fast=head;
ListNode* slow=head;
for (int i = 0; i < k; i++) {
/* code */
fast=fast->next;
}
while(fast->next)
{
fast=fast->next;
slow=slow->next;
}
ListNode*res=slow->next;
slow->next=NULL;
fast->next=head;
return res;
}
};