题解 | #链表中的节点每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类 */ //反转m的下一个到n void ReserveList(ListNode* m,ListNode* n) { ListNode* ss = m->next; ListNode* ssnext; n = n->next; m->next = n; //交换到n的下一个 while(ss != n) { ssnext = ss->next; ss->next = m->next; m->next = ss; ss = ssnext; } } ListNode* reverseKGroup(ListNode* head, int k) { // write code here if(head == nullptr) return head; //虚拟头结点,方便处理头结点head ListNode* virhead = new ListNode(-1); virhead->next = head; ListNode* fast = virhead; ListNode* slow = virhead; int pos = 0; //遍历链表,k个反转一次 while(fast != nullptr) { if(pos == k) { ListNode* temp = slow->next; ReserveList(slow,fast); slow = temp; fast = temp; pos = 0; } ++pos; fast = fast->next; } //销毁virhead返回他的下一个 fast = virhead->next; delete virhead; return fast; } };