61. 旋转链表
分析
注意 k >= n, k %= n
code
/**
* 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 NULL;
auto dummy = new ListNode(-1);
dummy->next = head;
int n = 0;
auto b = dummy;
for (auto p = head; p; p = p->next) {
b = p;
n ++;
}
if (k >= n) k %= n;
if (k == 0) return head;
k = n - k;
auto p = dummy;
for (int i = 0; i < k; i ++ ) p = p->next;
auto a = p->next; // 4
p->next = NULL;
b->next = dummy->next;
dummy->next = a;
return dummy->next;
}
};