lundi 12 juin 2017

Python seems to be ignoring the if statement within this class. What's going on?

So I'm writing up a linked list class, and one of the required function is inserting at a certain position. That's simple enough, and I have the code written for it, but I've also put together an error setup to keep someone from trying to add an element at an index that isn't there:

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

I feel like this should work, but whenever I try to insert an element that's larger than the size of the list, the code instead tries to work all the way to the end of the list (or past it)—where it tries to stick the data into a node that doesn't exist. I get this error: 'NoneType' object has no attribute 'nextnode'.

And that makes sense, but it shouldn't be going that far at all. How can I fix this?

Here's the full code, for context: http://ift.tt/2sUYsuN

Aucun commentaire:

Enregistrer un commentaire