/**
* 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 || !head){
return head;
}
ListNode* c = head;
int n = 1;
while(c->next){
c = c->next;
++n;
}
c->next = head; //连成一个环
int new_k = n - k % n; //转换成head指针从开始往后移动几次
ListNode* p = c;
c = head;
while(new_k--){
p = p->next;
c = c->next;
}
p->next = nullptr; //断开环尾
return c; //返回环头
}
};
LeetCode 61. 旋转链表
最新推荐文章于 2024-09-07 23:15:53 发布