0

When I want to add an element at the end of my linked list it result in an infinite loop, here's the method i used

#insert at the end of the list

def append(self, data=None):
    new_node = Node(data)
    if self.head is None:
        self.head = new_node
    itr = self.head
    while itr.next:
        itr.next = new_node
        itr = itr.next
6
  • do you want to add a single element or n numbers? Commented May 11, 2021 at 12:51
  • 2
    Please provide a minimal reproducible example Commented May 11, 2021 at 12:52
  • 1
    @Matiiss the OP is trying to implement a linked list. Commented May 11, 2021 at 12:53
  • @Sırrı Kırımlıoğlu I want to add n elements Commented May 11, 2021 at 12:59
  • Your loop is adding nodes infinitely to the end and looping through them. Commented May 11, 2021 at 13:01

2 Answers 2

1

Your code should return after adding the new node at the head if the list is empty.

After that your while loop is an infinite loop

You need to update it's position BEFORE you add to it and then add to it outside the loop

def append(self, data=None):
    new_node = Node(data)
    if self.head is None:
        self.head = new_node
        return
    itr = self.head
    while itr.next:
        itr = itr.next
    itr.next = new_node

Also your Node() should have a parameter for next

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

2 Comments

thanks a lot that really helps, one more question why my code should return after adding the new node at the head if the list is empty ? and and why it return nothing?
If the list is empty, adding the node is the end of the function. There's no reason to start looping through anything. You return nothing because it requires no output. It's just ending the function. Without the return, this code will add two nodes to an empty list.
1

Your problem is in the loop:

while itr.next:
   itr.next = new_node
   itr = itr.next

When appending an item to an empty list, itr is initially is equal to new_node. You set itr.next to new_node, so now new_node.next is equal to new_node. You have now created a cycle in your list, so it will loop forever.

When appending an item to your list, you should only be modifying the last element - the loop only serves to traverse the list to get to the end. It should look like:

def append(self, data=None):
    new_node = Node(data)
    if self.head is None:
        self.head = new_node
    else: 
        # you only need to traverse the list when it isn't empty
        itr = self.head
        while itr.next:
            itr = itr.next
        itr.next = new_node # only add the new node after traversing the list

That being said, this method of appending is O(n) complexity, and you can make it O(1) by keeping a pointer to the tail of the list and modifying the tail without traversing the list to find it.

Comments

Your Answer

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