这段代码有两个问题:

  1. reverseKGroup 函数中,for 循环的条件应该是 for (int i = 0; i < k; ++i),而不是 for (int i = 0; i <= k; ++i),因为 k 个节点只需要进行 k 次循环。

  2. 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;
}
C++ 翻转链表的 k 个节点:代码分析和优化

原文地址: https://www.cveoy.top/t/topic/oZKz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录