思路:
双指针法
1、判断链表是否为null
2.获取链表长度--遍历链表
3.向然first指针移动K个位置
4.只要first->next!=null 让second &first指针同时移动,直到first->next==null
5.将链表首尾相连--first->next=head 得到新的头指针--head=second->next 并断开环second->next=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==nullptr) return NULL;
int len=1;
//for (auto p=head ; p; p->next) n ++; //遍历链表,求得链表长度
ListNode *p=head;
while(p->next)
{
len++;
p=p->next;
}
k=k%len;
auto first=head,second=head;
while (k--)
{
first=first->next; //让指针first先走K个位置
}
while(first->next) //只要first->next 不为空,让此时的first和second一起移动
{
first=first->next;
second=second->next;
}
//遍历到最后一个位置时
first->next=head;
head=second->next;
second->next=NULL;
return head;
}
};
Every step of barefoot running deserves to be recorded