地址:
https://leetcode-cn.com/problems/rotate-list/
描述:
思路:
根据快慢指针的思想找到这个链表的倒数第k个数:
具体实现可以参考:https://blog.csdn.net/qq_52934831/article/details/119675084
代码:
/**
* 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==nullptr) return NULL;
int l=0;
ListNode *p=head;
while(p) {
p=p->next;
l++;
}
k=k%l;
//首先找到链表的的倒数第k个节点
ListNode *dummy=new ListNode(0,head);
ListNode *fast=dummy;
ListNode *slow=dummy;
//先让fast指针走k步
for(int i=0;i<k;i++) {
fast=fast->next;
}
//fast指针走到链表最后
while(fast->next){
fast=fast->next;
slow=slow->next;
}
//此时slow指针指向倒数第K+1个数,slow->next就是旋转后的头指针
fast->next=head;
head=slow->next;
slow->next=NULL;
return head;
}
};