题解 | #牛群旋转#
牛群旋转
https://www.nowcoder.com/practice/5137e606573843e5bf4d8ea0d8ade7f4
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* rotateLeft(ListNode* head, int k) {
// write code here
if (head == nullptr) {
return nullptr;
}
int len = 0;
ListNode* pre = head;
while (pre) {
len++;
pre = pre->next;
}
k %= len;
pre = head;
for (int i = 0; i < len-k-1; i++) {
pre = pre->next;
}
ListNode* h = pre->next;
ListNode* p = pre->next;
pre->next = nullptr;
while (p->next) {
p = p->next;
}
p->next = head;
return h;
}
};
