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

为何LeetCode可运行的移除链表元素代码在PyCharm报错?

问题原因与解决方法

错误原因

LeetCode平台处理链表题目时,会自动把输入的普通列表转换成ListNode类构成的链表结构,但你在PyCharm中直接传入普通列表[1,2,6,3,4,5,6],而列表对象没有val属性,执行到current_node.next.val时就触发了AttributeError。

解决步骤

要在本地正常运行代码,需要补充两个辅助逻辑:

  • 把普通列表转换成ListNode类型的链表
  • 把处理后的链表转回普通列表(方便打印查看结果)

修正后的完整代码

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        dummy_head = ListNode(-1)
        dummy_head.next = head

        current_node = dummy_head
        while current_node.next is not None:
            if current_node.next.val == val:
                current_node.next = current_node.next.next
            else:
                current_node = current_node.next

        return dummy_head.next

# 辅助函数:将普通列表转为ListNode链表
def list_to_linked_list(arr):
    dummy = ListNode(0)
    current = dummy
    for num in arr:
        current.next = ListNode(num)
        current = current.next
    return dummy.next

# 辅助函数:将ListNode链表转为普通列表
def linked_list_to_list(head):
    result = []
    current = head
    while current is not None:
        result.append(current.val)
        current = current.next
    return result

sol = Solution()
# 先转链表处理,再转回列表打印结果
linked_list = list_to_linked_list([1,2,6,3,4,5,6])
result_head = sol.removeElements(linked_list, 6)
print(linked_list_to_list(result_head))

代码说明

  • list_to_linked_list:遍历输入列表,逐个创建ListNode节点并串联成完整链表
  • linked_list_to_list:遍历处理后的链表,收集每个节点的val值到列表,直观展示结果
  • 调整removeElements的类型注解为ListNode(原[ListNode]是LeetCode的特殊写法,本地运行无需此格式)

内容的提问来源于stack exchange,提问作者IQ-Mming

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 02:52:16