Given a list, rotate the list to the right by k places, where k is non-negative.
For example: Given 1->2->3->4->5->nullptr and k = 2, return 4->5->1->2->3->nullptr.
思路。
1.链接成环
2.从首个节点,继续走len-k个节点,断环
//从右边起第K个位置旋转
LinkNode * rotate(LinkNode *head,int k)
{
LinkNode *dummy = new LinkNode(-1);
dummy->next = head;
LinkNode *cur = head;
LinkNode *pre,*tmp;
int len = 1;
//找到最后一个节点
while(cur->next)
{
len++;
cur=cur->next;
}
//连接成环
cur->next = head;
if(k>len)
k=k%len;
pre = dummy;
//从起点走len-k步,断开
for(int i=0;i<len-k;i++)
{
//找到断开的前驱节点
pre = pre->next;
}
tmp = pre->next;
pre->next = NULL;
dummy->next = tmp;
head=dummy->next;
delete dummy;
return head;
}