class Listnode: def __init__(self,val = 0,next = None): self.val = val self.next = next class MyLinkedList(): def __init__(self): self.dummyHead = Listnode() self.size = 0 def get(self,index): self.dummyHead = self.dummyHead.next for i in range(index): self.dummyHead = self.dummyHead.next return self.dummyHead.val def addAtHead(self,val): new_node = Listnode(val,None) new_node.next = self.dummyHead self.size +=1 """ dummyHead.next = Listnode(val,dummyHead.next) """ def addAtTail(self,val:int)->None: current = self.dummyHead.next while current: current = current.next #current.next = Listnode(val) self.size +=1 def addAtIndex(self,val:int,index:int)->None: current = self.dummyHead.next for i in range(index-1): current = current.next current.next = Listnode(val,current.next) def deleteAtIndex(self,index): current = dummyHead.next for i in range(index-1): current = current.next current.next = current.next.next #输入["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"][[], [1], [3], [1, 2], [1], [1], [1]] #输出[null, null, null, null, 2, null, 3] obj = MyLinkedList() obj.addAtHead(1) obj.addAtTail(3) obj.addAtIndex(1,2) param_1 = obj.get(1) obj.deleteAtIndex(1) param_2 = obj.get(1) print(param_1,param_2) 报错'NoneType' object has no attribute 'next'为什么
时间: 2024-01-13 08:05:49 浏览: 264
1_3.rar_visual c
在addAtTail方法中,当current遍历到链表最后一个节点时,current指向None,而在下一行代码中,current.next是NoneType,因此无法继续执行current.next = Listnode(val)的操作,导致出错。解决方法是在while循环中,将current指向最后一个节点,再执行current.next = Listnode(val)的操作。修改后的代码如下:
```
def addAtTail(self,val:int)->None:
current = self.dummyHead
while current.next:
current = current.next
current.next = Listnode(val,None)
self.size += 1
```
阅读全文