我的Bilibili频道:香芋派Taro
我的个人博客:taropie0224.github.io(阅读体验更佳)
我的公众号:香芋派的烘焙坊
我的音频技术交流群:1136403177
我的个人微信:JazzyTaroPie
https://leetcode.cn/problems/reverse-nodes-in-k-group/
题解and思路
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
| class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { if (head == nullptr) return head;
vector<int> vec; ListNode* node = head; while (node != nullptr) { vec.push_back(node->val); node = node->next; } ListNode* Head = new ListNode(); ListNode* Node = Head; int zheng = vec.size() / k; int yu = vec.size() % k; int times = -1;
for (int i = 0; i < zheng; i++) { times = times + k; for (int j = 0; j < k; j++) { ListNode* cur = new ListNode; cur->val = vec[times - j]; Node->next = cur; Node = cur; } } for (int i = 0; i < yu; i++) { ListNode* cur = new ListNode; cur->val = vec[times + 1 + i]; Node->next = cur; Node = cur; } return Head->next; } };
|