本地运行LeetCode链表题代码的类型标注与函数调用问题
本地调试LeetCode链表题方案
类型标注问题处理
代码里的ListNode是LeetCode平台内置预定义的链表节点类,本地运行需要自行定义该类;Optional需要从typing模块导入。在代码最开头添加以下内容即可:
from typing import Optional # LeetCode内置链表节点的本地实现 class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next
注:Python类型标注仅用于IDE类型提示,不会影响代码实际运行,就算省略标注只要逻辑正确也可正常执行。
链表构造与函数调用
直接传入Python原生列表的写法是错误的,middleNode接收的入参是链表头节点(ListNode实例),需要编写辅助方法完成普通列表和链表结构的互转,方便测试和结果查看。
辅助方法实现
def list_to_linked_list(lst): """输入普通Python列表,返回构造完成的链表头节点""" if not lst: return None head = ListNode(lst[0]) cur = head for val in lst[1:]: cur.next = ListNode(val) cur = cur.next return head def linked_list_to_list(node): """输入链表节点,返回从该节点开始的所有值组成的普通列表,便于打印结果""" res = [] while node: res.append(node.val) node = node.next return res
测试代码写法
注意你贴出的题解代码存在缩进错误,middleNode方法需要在Solution类下缩进4个空格,否则会触发语法错误。完整可运行代码如下:
from typing import Optional class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow def list_to_linked_list(lst): if not lst: return None head = ListNode(lst[0]) cur = head for val in lst[1:]: cur.next = ListNode(val) cur = cur.next return head def linked_list_to_list(node): res = [] while node: res.append(node.val) node = node.next return res if __name__ == "__main__": sol = Solution() # 测试用例 test_cases = [[1,2,3,4,5], [1,2,3,4,5,6]] for case in test_cases: head = list_to_linked_list(case) mid_node = sol.middleNode(head) print(f"用例{case}结果:{linked_list_to_list(mid_node)}")
运行后输出结果为:
用例[1,2,3,4,5]结果:[3,4,5] 用例[1,2,3,4,5,6]结果:[4,5,6]
上述两个辅助方法可以复用到所有链表类LeetCode题目的本地调试中,无需重复编写。
内容的提问来源于stack exchange,提问作者Lily
相关产品推荐
相关产品推荐

