2074.cpp (798B)
1 class Solution { 2 public: 3 ListNode *reverseEvenLengthGroups(ListNode *head) { 4 ListNode *prev = head, *crnt = head->next; 5 6 for (int lvl = 2; crnt; lvl++) { 7 ListNode *bg = prev; 8 9 int size = 0; 10 while (crnt && size < lvl) { 11 prev = crnt; 12 crnt = crnt->next; 13 size++; 14 } 15 16 if (size % 2) continue; 17 18 crnt = bg->next; 19 ListNode *last = crnt, *first = crnt, *tmp; 20 while (size--) { 21 tmp = crnt; 22 crnt = crnt->next; 23 tmp->next = last; 24 last = tmp; 25 } 26 bg->next = last; 27 first->next = crnt; 28 prev = first; 29 } 30 31 return head; 32 } 33 };