class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (head == nullptr) return head;
auto tail = head;
for(int i = 0; i < k; ++i) //先让tail移动k个节点
{
if(tail == nullptr) return head; //不足k个时
tail = tail->next;
}
ListNode* cur = head, *pre = nullptr, *next = nullptr;
while(cur != tail) //注意: reverse[head, tail)
{
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
head->next = reverseKGroup(tail, k); //@在本组中,head成为了最后一个节点,注意递归使用(tail, k)
return pre; //@返回翻转后的头结点
}
};
力扣25. K 个一组翻转链表
最新推荐文章于 2024-04-29 11:49:19 发布