You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode提交代码报NameError: 'Solution'未定义,请求排查问题

问题排查与解决方案

这个错误的核心原因是你提交的代码中没有定义LeetCode测试逻辑要求的Solution类,平台的驱动代码会自动调用Solution().reverseList(param_1),如果缺少这个类就会抛出NameError。

修复步骤

  1. 严格按照LeetCode的要求组织代码结构:必须定义全局的Solution类,并将反转链表的逻辑写在该类的reverseList方法中。
  2. 注意:LeetCode平台已经预先定义了ListNode类,无需自己重复编写(重复定义可能引发其他冲突)。

正确代码示例

class Solution:
    def reverseList(self, head):
        prev_node = None
        current_node = head
        while current_node:
            # 暂存下一个节点
            next_temp = current_node.next
            # 反转当前节点的指针
            current_node.next = prev_node
            # 移动指针
            prev_node = current_node
            current_node = next_temp
        return prev_node

额外注意事项

  • 确保Solution类是全局的,不要嵌套在其他函数或类内部。
  • 方法名必须为reverseList,参数和返回值要匹配题目给定的要求(比如参数是head,类型为ListNode)。

内容的提问来源于stack exchange,提问作者ng ng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 18:01:16