闭环断裂
- 思路:
- 将链表尾部链到头部,在旋转位置断开形成新的头部;
- 在迭代到尾部的过程中进行计数,计数闭环成环后需要偏移的最小步数(如果是链表 size 的整数倍回到原位置,实际不用旋转);
/**
* 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 (k == 0 || head == nullptr || head->next == nullptr) {
return head;
}
int size = 1;
ListNode* it = head;
// count & mv it to the tail
while (it->next != nullptr) {
it = it->next;
size++;
}
int shift = size - k % size;
if (shift == size) {
return head;
}
// ring back
it->next = head;
// then shift to break
while (shift--) {
it = it->next;
}
ListNode* result = it->next;
it->next = nullptr;
return result;
}
};