个人第一次解决hard级别题目
在反转链表的基础上,记录一个组的prev和next
首先记录改组的prev,通过curr指针的移动,移动到该组的最后一个,并且使用next记录下一组的开始、将 curr->next = nullptr;便于reverseList函数的执行 使用虚拟节点dummy作为虚拟头节点
还需注意的是: ①最后一组个数可能不足K,当curr == nullptr即可返回 ②最后一组个数刚好为K,那么while(!curr)循环条件不满足,退出循环 同时需要注意修改prev和curr
/**
* 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* reverse(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
ListNode* next = nullptr;
while(curr) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* dummy = new ListNode(0, head);
ListNode* prev = dummy;
ListNode* curr = head;
ListNode* next = nullptr;
while(curr) {
ListNode* tail = curr;
for(int i = 0; i < k - 1; i++) {
curr = curr->next;
if(!curr) {
return dummy->next;
}
}
next = curr->next;
curr->next = nullptr;
// 前与后连接
prev->next = reverse(tail);
tail->next = next;
prev = tail;
curr = next;
}
return dummy->next;
}
};