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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { if(k == 1) return head; ListNode* temp = new ListNode(); temp->next = head; int t = 0; vector<ListNode*> n(k+1, temp); while(n[0] != nullptr) { for(int i = 0; i < k; i++) { if(n[i]->next != nullptr) { n[i+1] = n[i]->next; } else return head; } if(t == 0) { head = n[k]; } for(int i = 1; i < (k/2) + 1; i++) { if(i == 1) { n[i-1]->next = n[k-i+1]; n[i]->next = n[k-i+1]->next; } else { n[k-i+2]->next = n[k-i+1]; n[i]->next = n[i-1]; } if(k%2 == 0 && i == k/2) { n[i+1]->next=n[i]; } else { n[k-i+1]->next = n[i+1]; n[k-i]->next = n[i]; } }
n[0] = n[1]; t++; }
return head; } };
|