如何解决属性错误:"列表"对象在python中没有属性"next"?


class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def insertionSortList(self, head):
head=[1]
dummy = ListNode()
curr = head

while curr:
# At each iteration, we insert an element into the resulting list.
prev = dummy

# find the position to insert the current node
while prev.next and prev.next.val < curr.val:
prev = prev.next

next = curr.next
# insert the current node to the new list
curr.next = prev.next
prev.next = curr

# moving on to the next iteration
curr = next

return dummy.next

test = [-1, 5, 3, 4, 0]
head = ListNode(test)
res_head = Solution().insertionSortList(head)

Traceback(最近调用last(:文件;无题.py";,第31行,inres_head=解决方案((.insertationSortList(head(文件"无题.py";,第19行,在insertionSortList中next=curr.next属性错误:"list"对象没有属性"next">

看起来您正在用列表[1]覆盖head,这将导致此错误。

def insertionSortList(self, head):
head=[1] # Head is being set to type list here

最新更新