Table of contents
Title description:
Problem-solving ideas:
Method: fast and slow pointer
Illustration:
Example: head=[1,2,3,4,5],k=2;
step:
Specific operation:
- First, we judge whether the linked list is empty, if it is empty, return head, if it is not empty, perform the following operations;
- Define a fast pointer fast and a slow pointer slow;
ListNode* fast=head; ListNode* slow=head;
- Let the fast pointer (fast) go k steps first;
for(int i=0;i>k;i++){ fast=fast->next; }
- At this point we have to consider whether k is greater than the length of the linked list , if it is less than the length of the linked list: if k is less than the length of the linked list, it is k in the for loop in the previous step; if k is greater than the length of the linked list, k in the for loop in the previous step must be calculated.
- According to the law, we found that k=k% the length of the linked list can be made , so that the two conditions are satisfied. We use a new function to calculate the length of the array;
int fun(LinsNode* head){ int len=0; while(head){ head=head->next; len++; } return len; }
- Then we make k=k%len execute the for loop;
- At this time, there is a difference of k bits between the fast (fast) and slow (slow) pointers, and then let them move together, and end the loop when fast->next == nullptr;
while(fast->next){ fast=fast->next; slow=slow->next; }
- The fast pointer (fast) goes to the end of the linked list, and then the next node points to the head node; the new head node points to slow; slow refers to empty and becomes the tail
fast->next=head; head=slow->next; slow->next=-nullptr;
Specific code:
class Solution {
public:
//先考虑k是否大于链表长度
int fun(ListNode* head){
int len=0;
while(head){
head=head->next;
len++;
}
return len;
}
ListNode* rotateRight(ListNode* head, int k) {
if(head==nullptr)return head;
//计算节点数
int len=fun(head);
k = k % len;
//快慢指针
ListNode* fast=head;
ListNode* slow=head;
//快指针先走k步
for(int i=0;i<k;i++){
fast=fast->next;
}
//快慢指针同时移动,直到fast->next==nullptr
while(fast->next){
fast=fast->next;
slow=slow->next;
}
//快指针到链表尾部,然后下一个结点指向头结点
fast->next=head;
//新的头结点指向slow
head=slow->next;
//slow指针指空,变成尾部
slow->next=nullptr;
return head;
}
};