题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ ListNode* reverseKGroup(ListNode* head, int k) { // write code here ListNode* dummyNode = new ListNode(-1); dummyNode->next = head; ListNode* cur = head; int cnt = 0; while(cur != nullptr){ cur = cur->next; cnt++; } int times = cnt/k; ListNode* prev = dummyNode; cur = head; while(times--){ ListNode* curNext = nullptr; for(int i = 0; i<k-1; i++){ curNext = cur->next; cur->next = curNext->next; curNext->next = prev->next; prev->next = curNext; } prev = cur; cur = cur->next; } return dummyNode->next; } };