Python实现单链表遇LeetCode运行时错误 是测试用例有误吗?
问题根因说明
- 运行时错误并非由非法测试用例导致,核心是代码的边界判断、越界处理逻辑与题目要求不匹配,具体问题如下:
1. 边界判断规则错误
- 对于
get、deleteAtIndex操作,合法索引范围是0 ≤ index < 链表长度,上界为小于长度,而非小于等于长度。 - 当前判断条件为
index < 0 or index > self.length,当索引等于链表长度时(比如链表长度为1时传入索引1),不会触发异常,直接进入删除逻辑后访问空指针,抛出AttributeError。
2. 越界处理不符合判题要求
- 测试用例传入越界索引是合法的输入场景,题目要求对越界操作做容错处理:
get越界时返回-1,无需抛出异常deleteAtIndex越界时直接终止操作,无需抛出异常
- 当前代码遇到越界就主动抛出
AssertionError,本身就不符合判题逻辑。
3. 其他代码缺陷
- 题目要求的主类名是
MyLinkedList,你定义的类名为SinglyLinkedList,会直接导致判题加载失败。 - 代码中使用的
SinglyListNode节点类未定义,需要自行实现包含val、next属性的节点结构。 - 当删除仅剩的最后一个节点时,需要同步将
head、tail都置为None,否则会残留野指针。
核心逻辑修复示例
修复后的get方法
def get(self, index): if index < 0 or index >= self.length: return -1 node = self.head for _ in range(index): node = node.next return node.val
修复后的deleteAtIndex边界逻辑
def deleteAtIndex(self, index): if index < 0 or index >= self.length: return # 越界直接返回,不执行任何操作 # 原有删除逻辑 if index == 0: self.head = self.head.next if self.length == 1: self.tail = None elif index == self.length - 1: self.tail = self.get(self.length - 2) self.tail.next = None else: node = self.head for _ in range(index - 1): node = node.next node.next = node.next.next self.length -= 1
内容的提问来源于stack exchange,提问作者Shrey Joshi
相关产品推荐
相关产品推荐

