LeetCode 61. 旋转链表
原题链接
中等
作者:
回归线
,
2021-03-27 22:13:08
,
所有人可见
,
阅读 161
/**
* 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) {
return head;
}
int n = 0;
for (auto a = head; a; a = a->next) {
++n;
}
k %= n;
if (!k) {
return head;
}
auto a = head;
for (int i = 0; i < n - k - 1; ++i) {
a = a->next;
}
auto b = a->next;
a->next = nullptr;
auto c = b;
while (c->next) {
c = c->next;
}
c->next = head;
return b;
}
};