1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class Solution { public: ListNode *reverseKGroup(ListNode *head, int k) { ListNode _header(0, head); ListNode *last = &_header; head = last; int count = 0; while (head) { head = head->next; count++; if (head && count == k) { count -= k; ListNode *tmp_last_next = last->next; reverseK(last, k); head = last = tmp_last_next; } } return _header.next; }
void reverseK(ListNode *start, int k) { ListNode *cur = start, *next = start->next; int count = 0; while (count < k) { ListNode *tmp = next->next; next->next = cur; cur = next; next = tmp; count++; } start->next->next = next; start->next = cur; } };
|