Python 似乎忽略了这个类中的 if 语句。这是怎么回事?



所以我正在编写一个链表类,其中一个必需的函数是在某个位置插入。这很简单,我有为它编写的代码,但我也整理了一个错误设置,以防止有人试图在不存在的索引处添加元素:

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

最新更新