题解 | #牛群的重新分组#
牛群的重新分组
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 if(!head || !k) { return head; } struct ListNode * m = head; int count = 0; while(m) { m = m->next; count++; } if(k > count) { return head; } struct ListNode * p = head->next; struct ListNode * q = head; struct ListNode * n = head; int num = k; while(num - 1) { n = p->next; p->next = q; q = p; p = n; n = n->next; num--; } head->next = reverseKGroup(p, k); head = q; return head; } };