题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ #include <cstddef> #include <ostream> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ ListNode* reverseKGroup(ListNode* head, int k) { if (head == NULL) { return NULL; } ListNode* num = new ListNode(-1); num = head; int j = 0; while (num != NULL) { num = num->next; j++; } int cut = j / k; ListNode* res = new ListNode(-1); res->next = head; ListNode* end = head; ListNode* start = res; for (int z = 0; z < cut; z++) { for (int i = 1; i < k; i++) { ListNode* temp = end->next; end->next = temp->next; temp->next = start->next; start->next = temp; } start=end; end=end->next; } return res->next; } };