Reputation: 11
So, I was coding a linked list in python using classes and after succesfullly defining and running all of the methods I setted up for the class, I decided to create an "insert" method, where you provide the data that you want to insert and the index of where you want it inserted.
After writing it, I tested it in a different file: I called the constructor, gave the list some data, by using a "push" method, and tried to insert another data by using the "insert" method.
What I ran up into was an endless loop - the data itself was inserted, but after trying to print all the content inside the list by using a for, it end up in a loop, printing the same data endlessly.
I checked the code a few times and tried to fix it, but the issue was still there.
Also, if I try to place the data on the head of the list, it doesn't get inserted.
Can someone explain to me what made the code go into this loop and how can I fix it, please?
Here's the code to the "insert" method and to the "Node" class that assists the Linked List class:
class Node:
'''To assist the linked list class'''
def __init__(self, content):
self.node = content
self.next = None
def insert(self, content, index: int = 0) -> bool:
'''Insert data in a specific index'''
if index == 0:
locate = Node(content)
locate.next = self.head
return True
else:
locate = self.head
for i in range(1, index):
locate = locate.next
if locate is None:
raise IndexError("Index out of range!")
temp = locate
aux = Node(content)
locate.next = aux
aux.next = temp
return True
Upvotes: 0
Views: 53
Reputation: 11
The first error is in "if index == 0:..."
When you insert it at the beginning, you must make the head the new node you inserted, so after "locale.next = self.head" you must add the code:
self.head = locate
Second error: After 'for', you point 'temp' to the same location as 'locate' (temp = locate) and then do the following
aux = Node(content)
locate.next = aux
aux.next = temp
Let's assume that locate and temp point to node B, this is the same thing to do:
aux = Node(content)
B.next = aux
aux.next = B
So your list looks like this:
B -> aux -> B
This forms a circle in the list and therefore enters an infinite loop.
To fix this you must change it so that:
temp = locate.next
Upvotes: 0