Good afternoon, I've been stumped with this for a while now. I have a doubly linked list with sentinel nodes created, and I'm trying to create a custom iterator to loop through said doubly linked list. My implementation of this is as follows:
def __iter__(self):
self.cur = self.__header
return self
def __next__(self):
for i in range(len(self)):
if self.cur.next != self.__trailer:
print('test')
print(i)
self.cur = self.cur.next
return self.get_element_at(i)
raise StopIteration
The self.__header
variable is referring to the head sentinel node upon which the rest of the list is linked. The self.__trailer
variable is referring to the tail sentinel node. What I am having an issue with is that say I have a doubly linked list called my_list
, with the following values 'Doubly', 'Linked', 'List'
. I then use the following code:
for node in my_list:
print(node)
to invoke the custom iterator. The expected output of this code should be
test
0
Doubly
test
1
Linked
test
2
List
However the actual output is as follows:
test
0
Doubly
test
0
Doubly
test
0
Doubly
Does anyone know what I am doing wrong? Thanks.