所以我写了一个链表类,其中一个必需的函数是在某个位置插入。这很简单,我已经为它编写了代码,但我还设置了一个错误设置,以防止有人试图在不存在的索引处添加元素:
def insert_element_at(self, data, position):
position=position-1 #gets around the difference between indexing and the way we count things
if position >= self.size:
print("Error: Index larger than current list size")
return
newnode=self.Node(data)
current=self.header
for i in range (0, position):
current=current.nextnode
newnode.nextnode=current.nextnode
current.nextnode=newnode
self.size=self.size+1
我觉得这个应该起作用,但是每当我尝试插入一个大于列表大小的元素时,代码就会一直工作到列表的末尾(或者超过它),它会尝试将数据粘贴到一个不存在的节点中。我得到这个错误:“NoneType”对象没有属性“nextnode”
这是有道理的,但它根本不应该走那么远。我怎样才能解决这个问题
以下是上下文的完整代码:https://pastebin.com/wgTLWWsx
可能问题是位置从0开始,大小从1开始,所以位置是4,大小是5
相关问题 更多 >
编程相关推荐