/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* tmp = head;
int n = 0;
// 记录n的个数
while(tmp != nullptr) {
n++;
tmp = tmp->next;
}
ListNode* pre = nullptr;
ListNode* dummy = new ListNode(0, head);
ListNode* cur = head, *p0 = dummy;
for(; n >= k; n -= k) {
for(int i = 0; i < k; i++) {
ListNode* nxt = cur->next;
cur->next = pre;
pre = cur;
cur = nxt;
}
ListNode* nxxt = p0->next;
p0->next->next = cur;
p0->next = pre;
p0 = nxxt;
}
return dummy->next;
}
};
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!