题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
/** * 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类 */ size_t GetListNodeCount(ListNode* head) { size_t count = 0; while (head != nullptr) { ++count; head = head->next; } return count; } ListNode* reverseKGroup(ListNode* head, int k) { if (head == nullptr) return head; if (k == 1) return head; auto len = GetListNodeCount(head); auto* pre = new ListNode(-1); auto* new_head = pre; pre->next = head; auto start = head; for (auto i = 0; i < len / k; ++i) { for (auto j = 0; j < k - 1; ++j) { auto temp = start->next; // 本题的思路和List的第二题一样,只不过是多了一步链表长度的计算 start->next = temp->next; // 同样使用头插法以及添加虚拟头作为previous结点的方法 temp->next = pre->next; pre->next = temp; } pre = start; start = start->next; } auto* ret = new_head->next; delete new_head; // 清理空间 return ret; } };#每天刷题#