合并两个链表出错
来源:4-5 Python数据结构常考题之链表

_不辞而别
2019-03-24
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
root = ListNode(x=None)
cur = root
while l1 and l2:
if l1.val <= l2.val:
cur.val = l1.val
cur.next = temp_node = ListNode(x=None)
cur = temp_node
l1 = l1.next
else:
cur.val = l2.val
cur.next = temp_node = ListNode(x=None)
cur = temp_node
l2 = l2.next
if l1:
cur.val = l1.val
cur.next = l1.next
else:
cur.val = l2.val
cur.next = l2.next
return root
老师您看一下我的代码哪里出错 了,在Leetcode上运行的时候是可以的,提交的时候就出现内部出错。请问哪里错了呢?
写回答
1回答
-
你提交的时候是可以看到错误的用例的。
考虑下当输入两个空链表的情况,代码会直接走到 这里,因为 l2 是 None,直接抛异常了
else: cur.val = l2.val cur.next = l2.next
AttributeError: 'NoneType' object has no attribute 'val'
Line 20 in mergeTwoLists (Solution.py)
Line 66 in main (Solution.py)
Line 74 in <module> (Solution.py)
10
相似问题