首页 > 解决方案 > 合并到链表,但出现不寻常的 None 类型错误

问题描述

合并两个排序的链表并将其作为新的排序列表返回。应该通过将前两个列表的节点拼接在一起来制作新列表。

例子:

输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(ListNode):
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        lst =[]
        while(l1!=None):
            #print("I")
            lst.append(l1.val)
            l1 = l1.next
        while (l2!=None):
            #print("I")
            lst.append(l2.val)
            l2 = l2.next
        lst.sort()
        #print(lst)
        l = ListNode(0)
        #temp : ListNode()
        temp = l
       # temp.val = l.val
        for i in lst:
            temp.val = i
            temp = temp.next
        return l

错误是

AttributeError: 'NoneType' object has no attribute 'val'
    temp.val = i

标签: pythonclassobjectlinked-list

解决方案


问题在于下面的行

temp = temp.next

您初始化temp为,l但它没有任何下一个元素,它只是一个元素。换句话说temp.nextNone每当您进行 for 循环的第二次迭代时,您都会看到AttributeError: 'NoneType' object has no attribute 'val'

解决方案:

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
lst = [1,2,3,4]

l = ListNode(lst[0])
temp = l
for i in lst[1:]:
    temp.next = ListNode(i)
    temp = temp.next

推荐阅读