题解 | #牛群的重新分组#
牛群的重新分组
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 vector<int> data; while(head != NULL) { data.push_back(head->val); head = head->next; } int n = data.size(); for (int i = 0; i < n; i += k) { int left = i; int right = min(i + k - 1, n - 1); // Ensure not to go beyond array bounds if (right - left + 1 == k) { // Check if there are enough elements to reverse while (left < right) { swap(data[left], data[right]); left++; right--; } } } ListNode* prev = new ListNode(0); ListNode* result = prev; for (auto it : data) { ListNode* cur = new ListNode(it); prev->next = cur; prev = cur; } return result->next; } };