题解 | #链表中的节点每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类 */ ListNode* reverseKGroup(ListNode* head, int k) { // write code here ListNode* dummy = new ListNode(0); dummy->next = head; ListNode* p = head; int n = 0; while(p) { p=p->next; n++; } ListNode* p0=dummy; ListNode* cur = p0->next; ListNode* pre = nullptr; ListNode* next = nullptr; while(n>=k) { n-=k; for(int i=1;i<=k;i++) { next = cur->next; cur->next = pre; pre = cur; cur = next; } next = p0->next; p0->next->next = cur; p0->next = pre; p0=next; } return dummy->next; } };