0

Im creating a python class to implement a doubly linked list. I have a seperate class for the DLL node itself and a class for the list. This is my class for the DLL nodes: class DLLNode:

def __init__(self,element,nextnode=None,prevnode=None,):

    self._element = element
    self._next = nextnode
    self._prev = prevnode

I have a method called insertAfter(self,x,y) which inserts node y after the first occurence x. Which is this :

if self.size != 0:
        n = DLLNode(y)
        if self.head._element == x:
            n._next = self.head._next
            self.head._next._prev = n
            n._prev = self.head
            self.head._next = n
            self.size += 1

        elif self.tail._element == x:
            self.tail._next = n
            n._prev = self.tail
            n._next = None
            self.tail = n
            self.size += 1
        else:
            iterator = self.head._next
            while iterator._next is not None:
                if iterator._element == x:
                    n._next = iterator._next
                    iterator._next._prev = n
                    n._prev = iterator
                    iterator._next = n
                    self.size += 1
                else:
                    iterator = iterator._next

when i run this function however, the function loops forever, when i kill the function myself, the error refers back to the 4th last line iterator._next = n it doesnt say anything else which is why im confused. Would greatly appreciate any help :)

1 Answer 1

1

In the loop

while iterator._next is not None:

in then branch you doesn't change iterator value. On every iteration both conditions iterator._next is not None (from while loop) and if iterator._element == x: are True (because iterator contain same value). And you get infinity loop. Try to add break at the end of then branch.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.