题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
http://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) { if (!head) return head; ListNode* cur = nullptr; ListNode* tail = nullptr; int i; for (i = 0; i < k && head; ++i){ auto tmp = head; head = head->next; tmp->next = cur; cur = tmp; if (!tail) tail = cur; } if (i < k) { return reverseKGroup(cur, i); } if (tail) tail->next = reverseKGroup(head, k); return cur; } };