https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
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 53
|
class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { if(k == 1) { return head; } ListNode * top = head; ListNode * ans; ListNode * ed = head;
int cnt = 0; int flag = 0; while(head != nullptr) { cnt++; if(cnt == k) { cnt = 0; ListNode * tmp = head -> next; ListNode * tmp3 = head -> next; ListNode * tmp4 = top; while(top != head) { ListNode * tmp2 = top -> next; top -> next = tmp; tmp = top; top = tmp2; } head -> next = tmp; if(flag == 0) { ans = head; flag = 1; } else { ed -> next = head; } ed = tmp4; top = tmp3; head = tmp3; } else head = head -> next; } return ans; } };
|
Author:
Qin Peng
License:
Copyright (c) 2020 BY QPWLKQ LICENSE
Slogan:
每一个不曾起舞的日子, 都是对生命的辜负