题解 | #链表中的节点每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 *res = new ListNode(0); res->next = head; ListNode *pre = res; ListNode *curr = head; int cnt = 0; //获取链表总长度 while(head) { ++cnt; head = head->next; } int n = cnt/k;//需要翻转的区间数 = 总长度/区间长度 for(int i = 0;i<n;++i) { //翻转k个结点时,需要进行k-1次操作 for(int j = 1;j<k;++j) { //头插法翻转该区间 ListNode *temp = curr->next; curr->next = temp->next; temp->next = pre->next; pre->next = temp; } pre = curr; curr = curr->next; } return res->next; } };