C++ 翻转链表的 k 个节点:代码分析和优化
这段代码有两个问题:
-
在
reverseKGroup函数中,for循环的条件应该是for (int i = 0; i < k; ++i),而不是for (int i = 0; i <= k; ++i),因为 k 个节点只需要进行 k 次循环。 -
在
ReverseList函数中,翻转链表的时候,需要记录每次翻转后的头节点,因为最后需要把翻转后的链表接到前面已经翻转的链表后面。修改方法如下:
ListNode* reverse(ListNode* head) {
if (head->next == nullptr) return head;
ListNode* hd = reverse(head->next);
head->next->next = head;
head->next = nullptr; // 添加这行代码
return hd;
}
原文地址: https://www.cveoy.top/t/topic/oZKz 著作权归作者所有。请勿转载和采集!