题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ #include <climits> class Solution { public: /** * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ ListNode* reverseKGroup(ListNode* head, int k) { // write code here if(k == 1) return head; ListNode* next = nullptr; ListNode* pre = nullptr; ListNode* p = head; ListNode* pre1 = nullptr; ListNode* pre2 = nullptr; int j = 0; while(p) { int l = 0; ListNode* p1 = p; while(p1&&l<k) { p1 = p1->next; l++; } if(l<k) { return head; } pre2 = pre1; pre1 = p; pre = p; p = p->next; for(int i=0;i<k-1;i++) { next = p->next; p->next = pre; pre = p; p = next; } pre1->next = p; if(pre2) pre2->next = pre; if(j==0) head = pre; j++; } return head; } };