题解 | #牛群的重新分组#
牛群的重新分组
https://www.nowcoder.com/practice/267c0deb9a6a41e4bdeb1b2addc64c93
/**
* 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* reverseKGroup(ListNode* head, int k) {
// write code here
ListNode *ppre=nullptr,*ppren=nullptr,
*pre=nullptr,*cur=head,
*fast=head,*tem=nullptr;
int i=k;
while(i--){
if(!fast) return head;
fast=fast->next;
}
//反转此区间链表
int j=k;
while(j--){
tem=cur->next;
cur->next=pre;//第一次反转时pre=nullptr,故此时cur->next=nullptr
pre=cur;
cur=tem;
}
head->next=reverseKGroup(fast, k);//最后一段不反转的返回头节点
return pre;//其余返回pre
}
};
